For example I have a class that call a function in its consturctor that returns local object. I'm trying to use rvalue references to get access to this object to avoid expensive move of it in memory.
class MyClass
{
BigObject&& C;
MyClass() : C(f())
{
};
};
BigObject f()
{
return BigObject();
}
But compiller tells me that reference member is initialized to a temporary that doesn't persist after the construction exits.
I don't get it. I understand that local objects, created in a scope of a function, exists only in a scope of function. Reaching the end of the scope - destructors of local objects are called. And here I initialize rvalue reference with local object , and I have access to it, while I'm in the body of constuctor.
Can someone explain, what is going on here? And is there a way to return a local object and use it as any ligetable class member, without moving it in memory?