lundi 15 novembre 2021

C++ 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 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.

Aucun commentaire:

Enregistrer un commentaire