Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does returning a standard container incur a copy of the contents of the container?

If I have a function that returns an STL container am I incurring a copy of the entire contents of the standard container?

e.g. Is this:

void Foo( std::vector< std::string >* string_list );

better than this:

std::vector< std::string > Foo();

Does it matter what's in the container? For instance would returning a container like this:

struct buzz {
    int a;
    char b;
    float c;
}

std::map< int, buzz > Foo();

be a more costly operation than this:

std::map< int, int > Foo();

Thanks, PaulH


Edit: This is with C++03. A C++0x solution is, unfortunately, not acceptable.

Edit2: I am using the Microsoft Visual Studio 2008 compiler.

like image 216
PaulH Avatar asked Dec 22 '22 17:12

PaulH


1 Answers

C++03 will probably do (named) return value optimization (google RVO and NRVO).

If that optimization is not applicable, C++0x will do move semantics.

like image 96
fredoverflow Avatar answered Dec 26 '22 10:12

fredoverflow