3 ms·
> Say I want to create a std::vector of objects. From what I understand, I have three options. Vectors already own their contents, so there is no need to use u
by hellofunk 10y ago
> Say I want to create a std::vector of objects. From what I understand, I have three options.
Vectors already own their contents, so there is no need to use unique_ptr here. The objects will be allocated on the heap either way, and you don't need a stack object either. Just push or emplace the object into your vector and be done with it. When the vector is deleted, so will its contents, automatically.
- Cyph0n 10y agoSo when I do something like this: http://i.imgur.com/WrRxXCm.png http://i.imgur.com/WrRxXCm.png Is there any overhead (e.g., copying or moving), or potential for memory leaks?
- hellofunk 10y agoYes. You will have a memory leak if you don't delete that memory later. But don't use new. Just push/emplace it into the vector. Perhaps ask more on stackoverflow.
- Cyph0n 10y agoYeah, your comment is confusing though: > The objects will be allocated on the heap either way, and you don't need a stack object either. Just push or emplace the object into your vector and be done with it. When the vector is deleted, so will its contents, automatically I guess what you mean to say is that emplace_back will do the allocation and lifetime management. But using push_back on a stack-allocated object is going to result in a copy.
- hellofunk 10y agoemplacement doesn't handle lifetime management; the vector itself does this, whether you emplace or push. push_back with a stack object will copy the object, yes. Emplace_back with a stack object will also, they are not much different. But if you emplace by creating the object inside the emplace call itself, then there is no copy. see the examples here: http://en.cppreference.com/w/cpp/container/vector/emplace_back http://en.cppreference.com/w/cpp/container/vector/emplace_ba...
- Cyph0n 10y agoThat makes sense. Thanks for the help man, and sorry if I bothered you!
- sbmassey 10y agoWell of course that is going to leak, but you could instead do std::vector<Person> v; Person p(10); v.emplace_back(p); and be safe
- hellofunk 10y agoEmplacing an object that already exists misses the point of emplacement.