Consider the code bellow.
// Consider that MyObject receives three integers in it's constructor.
MyObject createObject()
{
MyObject result(1, 2, 3);
return result;
}
As long as I know, when you return an object in C++(like in this function), the compiler will create a new object(as a local variable) in the stack for the client. In this exemple, it will be a new MyObject
object that will be created using the copy constructor with result
as parameter. This implies in redundant processing for the machine: the object result
will be created in the stack and then a second object will be created and returned.
An alternative to avoid this is creating the object dynamically(not in stack) and then return it's pointer. But it will cause memory leak or force the client to delete the object after use. So, the solution I found was to use an smart pointer, like this:
// Consider that MyObject receives three integers in it's constructor.
boost::smart_ptr<MyObject> createObject()
{
boost::smart_ptr<MyObject> result(new MyObject(1, 2, 3));
return result;
}
This works, but the smart pointer still is an object that will be recreated(even if the cost is low becouse, basically, it holds just a pointer). I was guessing if there's a way to do this a more easily; or if there wasn't a way already implemented by the compiler to optimize this work or something alike. Is there a syntax to say to the compiler to do what I want?
Profile your code first, I'm 99% sure there's no overhead from copying.
NRVO exists and will most probably kick in in this case.
If it weren't for copy elision, returning collections (like std::vector
and the likes) would cause massive problems.
when you return an object in C++(like in this function), the compiler will create a new object(as a local variable) in the stack for the client.
Not really. It will probably be created directly in the calling context, precisely to prevent the extra copy.