Possible Duplicate:
In C++, is it still bad practice to return a vector from a function?
In terms of performance, when needing to return’heavier’ objects like std::vector or std::string from a function, is it recommended to use this form:
void func(std::vector<int> *dest)
{
}
instead of this form:
std::vector<int> func()
{
std::vector<int> arr;
// ...
return arr;
}
I am assuming that the first form should be faster, but at the same time I’ve seen the second form often enough, the Qt API often returns a QString for example, probably because it is much more convenient or intuitive to use.
Also I’ve wondered if there are compiler optimizations which could remove the unnecessary copying of objects when using the return statement.
Edit
Are there any popular compilers still used today which do not perform the optimizations mentioned in the answers?
No.
A modern C++ compiler performs named return value optimisation (NRVO) which effectively means that the compiler reliably elides the copy here. No copy is performed.
Note that this is regardless of which C++ version you are using: C++03 does it as well as C++11. The only thing that changed in C++11 is that the language makes it easier for libraries to make moving out of a value (as is happening here) efficient when no copy elision can be performed.
For return values, copy elision can normally be performed – it’s more relevant in other cases (passing parameters by value, for instance). There are exceptions though; the following code cannot use named return value optimisation. It can use a C++11 move though:
The reason is that now two code paths return different named objects; this prevents NRVO.