我应该将C ++ 11 emplace_back与指针容器一起使用吗? [英] Should I use C++11 emplace_back with pointers containers?

查看:187
本文介绍了我应该将C ++ 11 emplace_back与指针容器一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有通常的基础->派生层次结构,例如:

Having a usual Base -> Derived hierarchy, like:

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

std::vector<Fruit*> m_fruits;

使用 emplace_back 而不是 push_back

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


推荐答案

指针是标量类型,因此是文字类型,依此类推复制,移动和放置构造(从左值或右值)都是等效的,通常将编译为相同的代码(标量副本)。 push_back 更清楚地表明您正在执行标量副本,而 emplace_back 应该保留给用于emplace构造的调用,复制或移动构造函数(例如,转换或多参数构造函数)。

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< Fruit> 而不是原始指针(以防止内存泄漏),因为您正在调用转换构造函数 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与指针容器一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆