gpt4 book ai didi

c++ - 为什么这个成员变量没有被正确初始化?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:04:31 25 4
gpt4 key购买 nike

刚刚偶然发现了这个,任何人都可以解释这里发生了什么吗?

struct Foo {
int i;
~Foo() {
std::cout << i << std::endl;
}
};

void bar()
{
Foo f;
f.i = 1;
f = Foo();
f.i = 2;
}

我得到以下输出:

-85899... (gibberish = "default" value for uninitialized int)
2

我期望的地方

1
2

为什么f.i = 1;在这里好像没有作用?

最佳答案

因此,在第一次调用析构函数时被销毁的变量不是f,而是Foo() 创建的临时变量。由于您没有构造函数,因此 i 具有不确定的值。如果您要添加一个将 i 设置为 99999 的构造函数,那么您会看到析构函数的输出。

void bar()
{
Foo f; // Construct f of type Foo
f.i = 1; // Set i to 1 in f.
f = Foo(); // Construct a temporary Foo object, copy it to f,
// then destroy the temporary object.
f.i = 2; // Set the newly copied f.i to 2.
// destroy f.
}

关于c++ - 为什么这个成员变量没有被正确初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16482559/

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