Static variable construction in C ++

How do compilers know how to properly handle this code?

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);

What will be the final value someOtherBaz.bar?

+3
source share
1 answer

The value someOtherBaz.barwill be 3.

Static objects in the translation block are built in the order in which they appear in TU (note: in different translation units there is no specific order of the static object).

  • First bazwill be constructed using the default constructor. This will set baz.barto 3.
  • someOtherBaz . , , . someOtherBaz.bar 3.
  • , placeholder baz.SetBar, baz ( someOtherBaz, , someOtherBaz baz, , ).

, :

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

Source: https://habr.com/ru/post/1732706/


All Articles