Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 236
static_rtti Avatar asked Sep 15 '10 19:09

static_rtti


People also ask

Can vector be returned in C++?

Yes, a function can return a vector in C++ and in different ways. This article explains the different ways in which a C++ function can return a vector. In order to code a vector in C++, the vector library has to be included in the program.

How do you return a vector STD?

In C++11, this is the preferred way: std::vector<X> f(); That is, return by value. With C++11, std::vector has move-semantics, which means the local vector declared in your function will be moved on return and in some cases even the move can be elided by the compiler.

How do you return a vector by reference?

vector<SalesItem> *getSalesItems(); returns a pointer and does not return a reference. void Invoice::getSalesItems() doesn't return anything. The function definition in the class and the declaration must be the same: vector<SalesItem> & getSalesItems(); returns a vector by refernece.

Can a function return a vector in C?

C programming does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.


1 Answers

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

like image 58
Steve Townsend Avatar answered Sep 30 '22 05:09

Steve Townsend