1

Currently using C++20, G++11.1.0.

What is the best way to add new elements to a vector of unique pointers?

I'm currently using vec.emplace_back(new Object), which works well for me. In some instances, just doing vec.emplace_back() works as well (not sure if its supposed to though).

After reading through this thread, I'm not sure what the best or safest method is. Should I even be using emplace_back? Or should I be using push_back instead?

spaL
  • 604
  • 7
  • 21
  • 1
    So is it good to use `vec.emplace_back(new Object)`? – spaL Jul 19 '22 at 05:53
  • I wouldn't expect `push_back` to work since `unique_ptr` is not copyable. – jkb Jul 19 '22 at 05:57
  • 3
    I would think `vec.emplace_back(make_unique())` should be used for exception safety. Perhaps somebody can confirm. `new`/`delete` should be avoided for normal code (not low level) as far as possible anyway (no RAII, exception safety and normally is red flag for not using smart pointers like `unique_ptr`). – Sebastian Jul 19 '22 at 05:57
  • 1
    @Sebastian What about `vec.emplace_back(make_unique())`? – spaL Jul 19 '22 at 06:00
  • Sorry, meant `make_unique` (what was I thinking/typing?), edited. – Sebastian Jul 19 '22 at 06:01
  • @jkb it is not copyable but moveable. `vec.push_back(std::make_unique())` should just work fine, as `push_back` supports move semantics. – Jakob Stark Jul 19 '22 at 06:01
  • @JakobStark Ah, forgot about that. Thanks. – jkb Jul 19 '22 at 06:04
  • `emplace_back` would probably save a move operation compared to `push_back` or is it optimized anyway? – Sebastian Jul 19 '22 at 06:07
  • 1
    @Sebastian Actually in this case the object is already constructed in `std::make_unique` so `emplace_back` calls the move constructor, while `push_back` calls the move assignment operator. I am pretty sure they do the same thing under the hood. – Jakob Stark Jul 19 '22 at 06:19
  • 3
    Note that `vec.emplace_back(make_unique())` and `vec.push_back(make_unique())` are effectively equivalent. You can use any of these. In this demo, GCC generated the exact same assembly for both: https://godbolt.org/z/cqr5EcxMY. – Daniel Langr Jul 19 '22 at 07:44
  • 1
    C++ Weekly had the topic emplace_back vs push_back covered in 2021 so this may be of some relevance here: https://youtu.be/jKS9dSHkAZY – std_unordered_map Jul 19 '22 at 07:46

0 Answers0