
[英]Assign std::vector<std::unique_ptr<T>> to another std::vector<std::unique_ptr<T>>
[英]What happens when std::make_unique<T>() assigns to std::unique_ptr<T>?
我对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?
传递给std::make_unique<A>()
的参数是传递给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) {}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.