When you return an stl vector from a function:
vector getLargeArray() { ... }
Is the return going to be an expensive copy operatio
You are very likely to get return value optimization, depending on the structure of the function body. In C++11 you could also benefit from move semantics. Returning by value certainly has cleaner semantics, and I would see it as the preferred option, unless profiling proves it to be costly. There is a good related article here.
Here is a small example with a verbose dummy class, compiled with no optimization or C++11 support, using an old-ish version of GCC (4.3.4):
#include
#include
struct Foo
{
Foo() { std::cout << "Foo()\n"; }
Foo(const Foo&) { std::cout << "Foo copy\n"; }
Foo& operator=(const Foo&) {
std::cout << "Foo assignment\n";
return *this;
}
};
std::vector makeFoos()
{
std::vector tmp;
tmp.push_back(Foo());
std::cout << "returning\n";
return tmp;
}
int main()
{
std::vector foos = makeFoos();
}
The result on my platform is that all copying happens before the function return. If I compile with C++11 support, then the push_back results in a move copy rather than a C++03 copy construction.