Recently I have run into a problem in a project. The code there is much more complicated than the following example but I hope the problem (if there is one) is the same.
#include <iostream>
class mObject
{
public:
mObject(){ std::cout << "mObject ctor\n"; }
mObject(const mObject& other){ std::cout << "mObject copy ctor\n"; }
~mObject(){ std::cout << "mObject dtor\n"; }
};
struct cFoo{
cFoo(const mObject& obj):obj_(obj){}
const mObject& get() { return obj_;}
const mObject& obj_;
};
mObject giveme() { return mObject(); }
void func2(const mObject& p) { mObject g = p; }
int main()
{
cFoo k(giveme());
func2(k.get());
return 0;
}
This gives me the following code:
mObject ctor
mObject dtor
mObject copy ctor
mObject dtor
So the original "temporary" mObject
instance dies before func2
usese it. I thought life time of a temporary object
is extended if there is a const&
to it. Assigning return of giveme()
to a local const&
in funtion main
solves this problem. Then the temporary lives until the end of the main
's scope. So what is going on here???