Search code examples
c++c++11smart-pointers

Should I use C++11 emplace_back with pointers containers?


Having a usual Base -> Derived hierarchy, like:

class Fruit { ... };
class Pear : Fruit { ... };
class Tomato : Fruit { ... };

std::vector<Fruit*> m_fruits;

Does it make sense (e.g: is performance better) to use emplace_back instead of push_back?

std::vector::emplace_back( new Pear() );
std::vector::emplace_back( new Tomato() );

Solution

  • Pointers are scalar types and therefore literal types, and so copy, move and emplace construction (from an lvalue or rvalue) are all equivalent and will usually compile to identical code (a scalar copy). push_back is clearer that you're performing a scalar copy, whereas emplace_back should be reserved for emplace construction calling a non-copy- or move- constructor (e.g. a converting or multi-argument constructor).

    If your vector should hold std::unique_ptr<Fruit> instead of raw pointers (to prevent memory leaks) then because you're calling a converting constructor emplace_back would be more correct. However that can still leak if extending the vector fails, so in that case you should use push_back(make_unique<Pear>()) etc.