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

前端 未结 5 1104
醉话见心
醉话见心 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 10:02

    Its essentially syntactic sugar for a user provided constructor which initializes the values. You are providing default values for data members. When you ask whether this happens at compile time or run time, the answer depends on the context its used in.

    Hopefully, these examples will help. Try them in http://gcc.godbolt.org and see the dissassembly and compilation errors.

    struct S { int size = 3; };
    
    //s's data members are compile time constants
    constexpr S s = {};
    
    //r's data members are run time constants
    const S r = {};
    
    //rr's data members are run time constants, 
    //but we don't know the values in this translation unit
    extern const S rr;
    
    template  class Foo {};
    
    //Ok, s.size is a compile time expression
    Foo f; 
    
    //Error, r.size is not a compile time expression
    Foo g; 
    
    //Compile time expression, this is same as return 3;
    int foo() { return s.size; }
    
    //This also works
    constexpr int cfoo() { return s.size; }
    
    //Compiler will optimize this to return 3; because r.size is const.
    int bar() { return r.size; }
    
    //Compiler cannot optimize, because we don't know the value of rr.size
    //This will have to read the value of rr.size from memory.
    int baz() { return rr.size; }
    

    As others have shown, static data members (and global variables, same thing essentially) for primitive types such as ints and floats have some weird rules where they can be const but still be used in compile time contexts as if they were constexpr. This is for backwards compatibility with C and the lack of the constexpr feature in the past. Its unfortunate now because it just makes understanding constexpr and what differentiates run time expressions from compile time expressions more confusing.

提交回复
热议问题