在成员初始值设定项列表中分配unique_ptr
Assignment of unique_ptr inside member initializer list
如果我有这个定义:
class A
{
A();
std::unique_ptr<B> m_b;
};
class B {};
如果我像这样初始化A
有区别吗:
A::A() : m_b(new B()) {}
与。
A::A() : m_b(std::make_unique<B>()) {}
此外,对于第一种情况,我是否可以确定我不必明确地致电delete
?
唯一的区别是风格。由于使用操作员new
现在被认为是老式的std::make_unique
因此建议使用。
对于编译器,没有区别。
顺便说一下应该是:
A::A() : m_b{std::make_unique<B>()} {}
另请参阅 CppCoreGuidelines/CppCoreGuidelines.md at master ·isocpp/CppCoreGuidelines
C.150:使用
make_unique()
构造unique_ptr
拥有的对象原因
例make_unique
对结构进行了更简洁的陈述。它还可确保复杂表达式中的异常安全。unique_ptr<Foo> p {new Foo{7}}; // OK: but repetitive auto q = make_unique<Foo>(7); // Better: no repetition of Foo // Not exception-safe: the compiler may interleave the computations of arguments as follows: // // 1. allocate memory for Foo, // 2. construct Foo, // 3. call bar, // 4. construct unique_ptr<Foo>. // // If bar throws, Foo will not be destroyed, and the memory-allocated for it will leak. f(unique_ptr<Foo>(new Foo()), bar()); // Exception-safe: calls to functions are never interleaved. f(make_unique<Foo>(), bar());
相关文章:
- 访问动态分配列表中的元素
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 如何将 QString 的 QList 分配给列表视图?
- 在成员初始值设定项列表中分配unique_ptr
- 使用列表进行动态结构分配
- C++初始化列表与分配值
- Unique_ptr:在列表中放置时未分配释放的指针
- 通过动态分配插入列表元素
- 我可以在 Boost.Spirit.Qi 中向列表运算符 (%) 提供内存分配提示吗?
- 将空初始化器列表分配给现有向量或地图的效果
- 如何删除列表中的动态分配类对象<T>?
- 声明变量以保存字符串列表时的内存分配
- 存储数据列表并自动分配给结构的最佳方法是什么
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 将节点添加到链接列表中,而无需明确分配内存空间(无需使用新)
- 删除为列表分配的内存
- 我应该重载哪个运算符来捕获列表分配
- 从初始值设定项列表分配给数组
- 正在为结构内部的列表分配空间
- 智能指针和参数列表分配规则