gpt4 book ai didi

c++ - C++中的静态变量构造

转载 作者:太空狗 更新时间:2023-10-29 19:55:25 24 4
gpt4 key购买 nike

编译器如何知道如何正确处理这段代码?

struct Foo
{
int bar;

Foo()
{
bar = 3;
}

Foo& operator=(const Foo& other)
{
bar = other.bar;
return *this;
}

int SetBar(int newBar)
{
return bar = newBar;
}
};

static Foo baz;
static Foo someOtherBaz = baz;
static int placeholder = baz.SetBar(4);

someOtherBaz.bar 的最终值是多少?

最佳答案

someOtherBaz.bar 的值为 3。

翻译单元中的静态对象按照它们在 TU 中出现的顺序构建(请注意,不同翻译单元中的静态对象没有定义的顺序)。

  1. 首先,baz 将使用默认构造函数构造。这会将 baz.bar 设置为 3。
  2. 接下来 someOtherBaz 将通过复制构造函数构造。由于没有定义复制构造函数,因此将使用默认的复制构造函数来复制每个字段。所以 someOtherBaz.bar 将被赋予 3 的值。
  3. 最后,为了构建placeholder,将调用baz.SetBar,这也会改变baz的值(但不是 someOtherBaz,因为它们是独立的对象;当您根据 baz 的值创建 someOtherBaz 时,它们是不同的对象,因此可以独立更改)。

所以,最后,您将拥有:

 baz.bar: 4
someOtherBaz.bar: 3
placeholder: 4

关于c++ - C++中的静态变量构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2259864/

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