Let’s say there is a function like
void SendToTheWorld(const Foo& f);
and I need to preprocess Foo object before sending
X PreprocessFoo(const Foo& f)
{
if (something)
{
// create new object (very expensive).
return Foo();
}
// return original object (cannot be copied)
return f;
}
Usage
Foo foo;
SendToTheWorld(PreprocessFoo(foo));
So X PreprocessFoo() function should be able to return original object or copy/modify and than return new one. I cannot return const Foo& as it may refer a temporary object. Also I don’t like to create Foo on the heap.
Perfectly, X should be some kind of union of const Foo& and Foo that may be treated as const Foo&. Any idea how to do that in more elegant way?
My current solution:
Foo PreprocessFoo(const Foo& f)
{
// create new object (very expensive).
return Foo();
}
Usage:
Foo foo;
if (something)
{
SendToTheWorld(PreprocessFoo(foo));
}
else
{
SendToTheWorld(foo);
}
I’m not 100% clear on what you mean but if you just want to omit an unnecessary copy of
Fooin the return value, make your function small (right now, it is) and rely on the optimizing compiler to take care of your problem.Once the function has been inlined, the compiler will elide unnecessary copies of
Foo.(Note for the interested: NRVO (named return value optimization) cannot be applied here since no unique name can be assigned to all instances of possible return values.)