Lambda Capture Life Time

Given the following program:

#include <iostream>
#include <memory>
using namespace std;
int main() {
    std::shared_ptr<int> i(new int(42));
    cout << i.use_count() << endl;
    auto fn = [=](){i; cout << 42 << endl;};
    cout << i.use_count() << endl;
    return 0;
}

When the compiler decides which objects it will capture?
The value of shared_ptr is inever used in a lambda expression. Therefore, in a normal function, I would suggest that the optimizer removes this nop statement.
But if it is removed, the compiler might think that there is ino need to write.

Thus, with gcc, this program will always output 1.2 as output.
But is this guaranteed by the standard?

+4
source share
2 answers

If you go to the cppreference page in a lambda function , they have the following explanation:

[=] , ,

:

, , . ( odr ) = ( odr ).

odr-used :

odr, , , :

  • lvalue-to-rvalue exression ,
  • , lvalue-to-rvalue

i, i .

draft ++ 11, 5.1.2 -, 11, :

- odr-uses (3.2) this , odr, , , odr, ; .

+2

[=] , odr . odr:

, , odr, , , lvalue-rvalue.

i ; odr-used ; , .

?

tl; dr yes.

+2

All Articles