scope - Lifetime of C++ temporary extended to lexical when assigned to const& -
this question has reply here:
lifetime of temporaries 2 answersi suprised find temporary variable in c++ beingness promoted having total lexical scope:
class foo { public: foo() { std::cout << "a"; } ~foo() { std::cout << "b"; } }; int main(void) { // prints "acb", showing temporary beingness promoted having lexical scope. const foo& f = foo(); std::cout << "c"; homecoming 0; } aside dubious behavior of assigning temporary reference, works fine (tested in vs2010 , g++ v4.1). output acb, showing temporary object has been promoted having lexical scope, , destructed @ end of function (b printed after c).
other temporary variables don't behave way:
int main(void) { // prints "acbd", showing temporary destroyed before next sequence point. const int f = ((foo(), std::cout << "c"), 5); std::cout << "d"; homecoming 0; } as per code comment prints acbd, showing temporary variable kept until entire look has finished evaluating (why c printed before b), still destroyed before next sequence point (why b printed before d). (this behaviour how thought temporary variables in c++ worked. surprised @ before behaviour.)
can explain when legal temporary promoted have lexical scope this?
the lifetime of temporary bound constant lvalue reference or rvalue reference (since c++11) extended lifetime of reference. in sec case not have reference on left side of assignment, value, lifetime of temporary not prolonged.
see 12.2/4 , 12.2/5 of c++ 11 standard:
there 2 contexts in temporaries destroyed @ different point end of fullexpression. first context when default constructor called initialize element of array [...]
the sec context when reference bound temporary. temporary reference bound or temporary finish object of subobject reference bound persists lifetime of reference except: [...]
what follows "except" situations not apply case.
c++ scope lifetime
No comments:
Post a Comment