mardi 24 avril 2018

When the move constructor is actually called if we have (N)RVO?

I have understood from several questions here on SO that (N)RVO prevents the move constructor from being called, when an object is returned by value. Classic example:

struct Foo {
  Foo()            { std::cout << "Constructed\n"; }
  Foo(const Foo &) { std::cout << "Copy-constructed\n"; }
  Foo(Foo &&)      { std::cout << "Move-constructed\n"; }
  ~Foo()           { std::cout << "Destructed\n"; }
};

Foo makeFoo() {
  return Foo();
}

int main() { 
  Foo foo = makeFoo(); // Move-constructor would be called here without (N)RVO
}

The output with (N)RVO enabled is:

Constructed
Destructed

So in what cases the move constructor would be called, regardless the (N)RVO presence? Could you provide some examples? In other words: why should I care implementing a move constructor if the (N)RVO does its optimization job by default?

Aucun commentaire:

Enregistrer un commentaire