Proper way (move semantics) to return a std::vector from function calling in C++11

Loom picture Loom · Jun 2, 2011 · Viewed 19.8k times · Source

I want to fill std::vector (or some other STL container):

class Foo {
public:
  Foo(int _n, const Bar &_m);
private:
  std::vector<Foo> fooes_;
}

1.Good looking ctor, expensive performance

std::vector<Foo> get_vector(int _n, const Bar &_m) {
  std::vector<Foo> ret;
  ... // filling ret depending from arguments
  return ret;
}

Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}

2. Better performance, worse looking ctor

void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
  ... // filling ret depending from arguments
}

Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }

Is it possible to rewrite get_vector function from 1st example with C++0x (move semantics features and so on) to avoid redundant copying and constructor calls?

Answer

John Calsbeek picture John Calsbeek · Jun 2, 2011

If you're using a C++0x-compatible compiler and standard library, you get better performance from the first example without doing anything. The return value of get_vector(_n, _m) is a temporary, and the move constructor for std::vector (a constructor taking an rvalue reference) will automatically be called with no further work on your part.

In general, non-library writers won't need to use rvalue references directly; you'll just reap a decent chunk of the benefits automatically.