C++11 vector with smart pointer

I read a lot of documentation about vector modern usage.

One of the common thing appearing is, "you can replace every push_back by emplace_back". Is it true ? I'm unsure, and the fact is I don't get the idea with a smart pointer.

So, is there a difference to emplace a smart pointer than pushing it into the vector ?

In other words :

myVector.emplace_back(std::make_shared< XXX >(x, y, z));

VS

myVector.push_back(std::make_shared< XXX >(x, y, z));

I read a comment about emplacing a smart pointer and a possible exception (low memory) raised just before the insertion leading to a memory leak. Is it true ? Memory leaking

And finally, I was hoping to write something like this :

myVector.emplace_back(x, y, z);

But I'm pretty sure, I can forget it. So that's why I'm thinking about the real benefits of emplace with smart pointers.

Upvotes: 1

Views: 792

Answers (1)

Caleth
Caleth

Reputation: 62686

There's no difference between the emplace_back and push_back at the start of your question, they both supply a prvalue std::shared_ptr<XXX> that will be passed to the move constructor of the vector element.

You can't myVector.emplace_back(x, y, z); if myVector holds std::shared_ptr<XXX> because there's no constructor of std::shared_ptr<XXX> that takes those arguments. You could do that if it were a std::vector<XXX>, and that would construct one XXX in-place.

Much of this is moot however, because copy elision means that an implementation is allowed to construct the shared pointer in place.

Upvotes: 2

Related Questions