在成员初始值设定项列表中分配unique_ptr

Assignment of unique_ptr inside member initializer list

本文关键字:列表 分配 unique ptr 成员      更新时间:2023-10-16

如果我有这个定义:

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());