lundi 30 novembre 2015

Use of std::move in parameter construction

I'm trying to construct an object from a function and later pass it to a function that uses it (and consumes it). Here's the code

std::unique_ptr<Object> createObject() {
  auto myobj = std::make_unique<Object>();
  .. modify myobj ..
  return std::move(myobj);
}

void consumeObject(Object&& robj) {
  myvector.emplace_back(std::forward<Object>(robj));
}


consumeObject(createObject()); // Is this right?

I'm not using rvalue references directly from the createObject since I would return a reference to deallocated memory.

Is std::move necessary in the part indicated in the code? What happens if, like I did in the code above, I pass a rvalue to be bound to the rvalue reference? The code seems to compile just fine but I can't see the difference between a

consumeObject(createObject());

and

consumeObject(std::move(createObject()));

Aucun commentaire:

Enregistrer un commentaire