Imagine such situation that I have a function like this:
Object f()
{
Object obj;
return obj;
}
Where sizeof(Object) is a big value.
And then I make a call of this function:
Object object = f();
Do i understand correctly that first Object will be created on a stack (in the function) and then will be copied to object variable?
If so, is it reasonably to create an object in the function on a heap and to return a pointer to it instead of a copy ?
But i mean that the object must be created in the f() function – not passed by a pointer or a reference to this function and initialized.
EDIT
I don’t mean that f is a very simple function. It can have a really complex routine of object initialization depending on some context. Will the compiler still optimize it as well?
For that specific case, you can take advantage of the fact that compilers nowadays are smart enough to optimize for it. The optimization is called named return value optimization (NRVO), so it’s okay to return “big” objects like that. The compiler can see such opportunities (especially in something as simple as your code snippet) and generate the binary so that no copies are made.
You can also return unnamed temporaries:
This invokes (unnamed) return value optimization (RVO) on just about all modern C++ compilers. In fact, Visual C++ implements this particular optimization even if all optimizations are turned off.
These kinds of optimizations are specifically allowed by the C++ standard:
Generally, the compiler will always try to implement NRVO and/or RVO, although it may fail to do so in certain circumstances, like multiple return paths. Nevertheless, it’s a very useful optimization, and you shouldn’t be afraid to use it.
If in doubt, you can always test your compiler by inserting “debugging statements” and see for yourself:
If the returned object isn’t meant to be copyable, or (N)RVO fails (which is probably not likely to happen), then you can try returning a proxy object:
Of course, this isn’t exactly obvious so proper documentation would be needed (at least a comment about it).
You can also return a smart pointer of some kind (like
std::auto_ptrorboost::shared_ptror something similar) to an object allocated on the free-store. This is needed if you need to return instances of derived types: