Consider the following function that returns a big object:
std::list<SomethingBig> DoSomething()
{
std::list<SomethingBig> TheList;
//do stuff
return TheList;
}
I want to get the list, not a copy of it. Because if I have to copy such objects, the performance price is expensive. I know return-value optimization may take care of this for me, but depending on optimizations to optimize bad code is not the best way to go (right?).
A clean way to avoid copying and extend the life of an object, is using a constant reference (and please test it before calling it a dangling reference, because it's not):
const std::list<SomethingBig>& theList = DoSomething();
In C++11, one could use std::move
to avoid copying. However, I'm working on a C++03 program, and I have to do this:
const std::list<SomethingBig>& list1 = DoSomething();
const std::list<SomethingBig>& list2 = DoSomethingElse();
and now I need to splice the lists together. The only way for me to do that is either copy everything, or const_cast
these lists and splice them. Is there a better solution?