Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 当std::make_unique<;T>;()分配给std::unique_ptr<;T>;?_C++_C++11_Smart Pointers - Fatal编程技术网

C++ 当std::make_unique<;T>;()分配给std::unique_ptr<;T>;?

C++ 当std::make_unique<;T>;()分配给std::unique_ptr<;T>;?,c++,c++11,smart-pointers,C++,C++11,Smart Pointers,我对std::unique\u 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 <<

我对std::unique\u 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的结果值为0


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

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

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

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

初始化它们:

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

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

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

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

初始化它们:

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

我还想强调的是,这种行为与
std::unique\u ptr
@r3musn0x-Fixed无关。我还想强调的是,这种行为与
std::unique\u ptr
@r3musn0x-Fixed无关