C++ 当std::make_unique<;T>;()分配给std::unique_ptr<;T>;?
我对std::unique\u ptr有一个疑问 当我们为没有参数的std::make_unique()赋值时,会发生什么 比如说,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 <<
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无关