Returning a c++ std::vector without a copy?

static_rtti picture static_rtti · Sep 15, 2010 · Viewed 32.3k times · Source

Is it possible to return a standard container from a function without making a copy?

Example code:

std::vector<A> MyFunc();

...

std::vector<A> b = MyFunc();

As far as I understand, this copies the return value into a new vector b. Does making the function return references or something like that allow avoiding the copy?

Answer

Steve Townsend picture Steve Townsend · Sep 15, 2010

If your compiler supports the NRVO then no copy will be made, provided certain conditions are met in the function returning the object. Thankfully, this was finally added in Visual C++ 2005 (v8.0) This can have a major +ve impact on perf if the container is large, obviously.

If your own compiler docs do not say whether or not it's supported, you should be able to compile the C++ code to assembler (in optimized/release mode) and check what's done using a simple sample function.

There's also an excellent broader discussion here