I have read many articles regarding the lifetime of a temporary and it seems the lifetime of temporary object is extended in certain cases, while in the rest of the cases, its a dangling object.
In my case the temporary object is returned from a function, I want to understand if the const ref to the temporary object will remain valid or not.
Here is the code:
class MyClass
{
public:
std::vector<int> vec{ 1, 2 };
MyClass()
{
cout << "Ctor" << endl;
}
MyClass(const MyClass ©)
{
vec = copy.vec;
cout << "Copy Ctor" << endl;
}
~MyClass()
{
cout << "Dtor" << endl;
}
};
MyClass access()
{
MyClass obj;
obj.vec[0] = 10;
return obj;
}
int main()
{
{
const auto &ret = access(); // calls the copy-ctor and assigns the temporary to reference 'ret'
auto val = ret.vec[0];
cout << "By Ref = " << val << endl; // works fine
}
cout << "_____________________________________" << endl;
{
const auto *ret = &access(); // temporary is lost
auto val = ret->vec[0]; // program crash
cout << "By Pointer = " << val << endl;
}
return 0;
}