gpt4 book ai didi

c++ - 当 std::make_unique() 赋值给 std::unique_ptr 时会发生什么?

转载 作者:行者123 更新时间:2023-11-28 01:25:41 24 4
gpt4 key购买 nike

我对 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 的默认构造函数将被调用。

Why default constructor not assign the int as 0 when using std::make_unique()?

未初始化的内置类型成员留下不确定的值。此行为与 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) {}
};

关于c++ - 当 std::make_unique<T>() 赋值给 std::unique_ptr<T> 时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53984664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com