C++中的静态变量构造

Cla*_*bel 3 c++

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

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);
Run Code Online (Sandbox Code Playgroud)

最终价值someOtherBaz.bar是多少?

R S*_*hko 10

价值someOtherBaz.bar将是3.

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

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

所以,最后,你将拥有:

 baz.bar: 4
 someOtherBaz.bar: 3
 placeholder: 4
Run Code Online (Sandbox Code Playgroud)

  • @legend22K - 代码中没有赋值 - = 符号的使用不是赋值,而是复制构造函数调用。 (2认同)