Does in class member initialization takes place at compile time or run-time?

前端 未结 5 1110
醉话见心
醉话见心 2021-02-02 09:42

In C++11 a new feature was introduced where the programmer can initialize class member variables inside class\'s definition, see code below:

struct foo
{ 
  int         


        
5条回答
  •  逝去的感伤
    2021-02-02 10:06

    First of all yes, as stated before, it is syntactic sugar. But since the rules can be too much to remember, here's a logical experiment to help you figure out what happens in compile time and what not

    You have your c++11 class that features in class initializers

    struct foo { int size = 3; };
    

    And another class that will help us with our experiment

    template
    struct experiment { enum { val = N }; };
    

    Let our hypothesis H0 be that initialization does happen in compile time, then we could write

    foo                a;
    experiment b;
    

    No luck, we fail to compile. One could argue that failure is due to foo::size being non constant so lets try with

    struct foo { const int size = 3; }; // constexpr instead of const would fail as well
    

    Again, as gcc informs us

    the value of ‘a’ is not usable in a constant expression

    experiment b;

    or (more clearly) visual studio 2013 tells us

    error C2975: 'N' : invalid template argument for 'example', expected compile-time constant expression

    So, we have to discard H0 and deduce that initialization does not happen in compile time.

    What would it take to happen in compile time

    There is an old syntax that does the trick

    struct foo { static const int size = 3; };
    

    Now this compiles but beware this is (technically and logically) no longer in class initialization.

    I had to lie for a little to make a point, but to expose the whole truth now : Message errors imply that a is the real problem. You see, since you have an instance for an object (Daniel Frey also mentions this) memory (for members) has to be initialized (at runtime). If the member was (const) static, as in the final example, then it's not part of the subobjects of a(ny) class and you can have your initialization at compile time.

提交回复
热议问题