I tried this with gcc. I realized that I can not rely on NRVO when compiling without C ++ 11 flags.
Since I do not like the second signature (where the function accepts the container by reference), I got the following:
Declare a function in its natural form:
vector<T> func(){ vector<T> result; ... return result; }
and when I'm not sure about the compiler and compilation flags, use it like this:
vector<T> result; func().swap(result)
Thus, you get the required interface and be sure to avoid flexible overhead.
Note that the capacity of the result vector is the vector returned by the function. If you want to set the capacity for the vector, the right interface for the function is second.
source share