首页 > 解决方案 > 当 std::make_unique 发生什么() 分配给 std::unique_ptr?

问题描述

我对 std::unique_ptr 有一个疑问。

当我们分配没有参数的 std::make_unique() 时,会发生什么?

例如,

struct A {
  int a, b;
  A() {}
  A(int w, int e) : a(w), b(e) {}
};

int main() {
   A h(1, 2);
   std::unique_ptr<A> hello = std::make_unique<A>();
   std::cout << hello->a << std::endl;
}

在上面的代码中,我提到了默认构造函数,我得到了 hello->a 的输出作为垃圾值(随机负值)

但是,当我如下更改结构时,

struct A {
  int a, b;
  A() {a=0;b=0;}
  A(int w, int e) : a(w), b(e) {}
};

hello->a 的结果值为 0。

为什么在使用 std::make_unique() 时默认构造函数不将 int 分配为 0?

标签: c++c++11smart-pointers

解决方案


传递给std::make_unique<A>()的参数是传递给 的相应构造函数的参数A。在这里您没有提供任何内容,因此A将调用默认构造函数。

为什么在使用 std::make_unique() 时默认构造函数不将 int 分配为 0?

未初始化的内置类型的成员留下一个不确定的值。此行为与std::unique_ptror无关std::make_unique;这就是默认初始化内置类型的方式。

初始化它们:

struct A {
  int a, b;
  A(): a(0), b(0) {}
  A(int w, int e) : a(w), b(e) {}
};

推荐阅读