我应该使用C ++ 11 emplace_back指针containters? [英] Should I use C++11 emplace_back with pointers containters?
问题描述
有一个通常的Base - > Derived层次结构,如:
Having a usual Base -> Derived hierarchy, like:
class Fruit { ... };
class Pear : Fruit { ... };
class Tomato : Fruit { ... };
std::vector<Fruit*> m_fruits;
使用emplace_back而不是push_back才有意义>
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() );
推荐答案
指针是标量类型,复制,移动和emplace构造(从左值或右值)都是等效的,并且通常将编译为相同的代码(标量副本)。 push_back
更清楚你正在执行一个标量副本,而 emplace_back
复制或移动构造函数(例如转换或多参数构造函数)。
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).
如果你的向量应该持有 std :: unique_ptr&
而不是原始指针(以防止内存泄漏),因为你正在调用转换构造函数 emplace_back
会更正确。然而,如果扩展向量失败,仍然可能泄漏,所以在这种情况下,您应该使用 push_back(make_unique< Pear>())
等。
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.
这篇关于我应该使用C ++ 11 emplace_back指针containters?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!