#include <iostream> using namespace std; struct CL { CL() { cout<<"CL()"<<endl; } CL(const CL&) { cout<<"CL(const CL&)"<<endl; } ~CL() { cout<<"~CL()"<<endl; } }; CL cl; CL fnc() { return cl; } int main() { cout<<"start"<<endl; const CL& ref=static_cast<const CL&>(fnc()); //...Is "ref" valid here?? cout<<"end"<<endl; return 0; }
What is the lifetime of a temporary object returned by fnc ()? Is it the "ref" lifetime or the temporary reference static_cast (fnc ()) that was destroyed at the end of the statement?
Gcc output (fnc () lifetime is the "ref" lifetime):
CL() //global object "cl" start CL(const CL&) end ~CL() ~CL() //global object "cl"
VS2013 output (fnc () lifetime - time reference lifetime):
CL() //global object "cl" start CL(const CL&) ~CL() end ~CL() //global object "cl"
What is correct by standard?
c ++ reference language-lawyer temporary-objects
user3514538
source share