Having a usual Base -> Derived hierarchy, like:
class Fruit { ... };
class Pear : Fruit { ... };
class Tomato : Fruit { ... };
std::vector<Fruit*> m_fruits;
Has it sense (e.g: it has better performance) to use emplace_back instead of push_back?
std::vector::emplace_back( new Pear() );
std::vector::emplace_back( new Tomato() );
Don't use raw pointers, use
std::unique_ptr
like this:And as you can't copy construct a
std::unique_ptr
you must useemplace_back
(although you can usepush_back
withstd::move
).Edit:
As it appears that using
std::vector<std::unique_ptr<T>>::emplace_back
andnew
can leak if thestd::vector
needs and fails to reallocate memory, my recommended approach (until C++14 introducesstd::make_unique
) is to usepush_back
like this:Or using
std::make_unique
: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, whereasemplace_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 constructoremplace_back
would be more correct. However that can still leak if extending the vector fails, so in that case you should usepush_back(make_unique<Pear>())
etc.