c++ - Lifetime of rvalue bound to static const reference -
consider this:
std::string foo(); void bar() { const std::string& r1 = foo(); static const std::string& r2 = foo(); }
i know lifetime of string resulting first call foo()
extended lifetime of r1
.
what temporary bound r2
, though? live until end of scope or still there when bar()
re-entered?
note: not interested whether particular compiler so. (i interested in 1 use, , can test that.) want know standard has on this.
the temporary extended the lifetime of reference.
[c++14: 12.2/5]:
the temporary reference bound or temporary complete object of subobject reference bound persists lifetime of reference except:
- a temporary bound reference member in constructor’s ctor-initializer (12.6.2) persists until constructor exits.
- a temporary bound reference parameter in function call (5.2.2) persists until completion of full-expression containing call.
- the lifetime of temporary bound returned value in function return statement (6.6.3) not extended; temporary destroyed @ end of full-expression in return statement.
a temporary bound reference in new-initializer (5.3.4) persists until completion of full-expression containing new-initializer. [ example:
struct s { int mi; const std::pair<int,int>& mp; }; s { 1, {2,3} }; s* p = new s{ 1, {2,3} }; // creates dangling reference
—end example ] [ note: may introduce dangling reference, , implementations encouraged issue warning in such case. —end note ]
(in particular, note none of bullet points match scenario.)
so, in case, it's until program ends.
we can, of course, test pretty trivially:
#include <iostream> struct tracked { tracked() { std::cout << "ctor\n"; }; tracked(const tracked&) { std::cout << "copy\n"; }; ~tracked() { std::cout << "dtor\n"; }; }; void foo() { static const tracked& ref = tracked(); } int main() { std::cout << "main()\n"; foo(); std::cout << "bye\n"; }
result:
main()
ctor
bye
dtor
Comments
Post a Comment