简体   繁体   中英

Why does a user-provided constructor allow for instantiation of a const class instance?

Here is an example from cpp reference.

struct T1 { int mem; };

struct T2
{
    int mem;
    T2() { } // "mem" is not in the initializer list
};

int main()
{
    //  const T1 t1;  // error: const class with implicit default ctor
    T1 t1;            // class, calls implicit default ctor
    const T2 t2;      // const class, calls the user-provided default ctor
                      // t2.mem is default-initialized (to indeterminate value)
}

In the example, // const T1 t1; // error: const class with implicit default ctor // const T1 t1; // error: const class with implicit default ctor makes sense because if that was allowed then it would make mem an uninitialized const member that cant be changed.

But the third one,

 const T2 t2;      // const class, calls the user-provided default ctor
                   // t2.mem is default-initialized (to indeterminate value)

It says, // const class, calls the user-provided default ctor . Now this doesn't make sense to me because the constructor still isn't initializing mem. Then it goes on to say // t2.mem is default-initialized . How?

I would understand this if the constructor initialized mem . Something like:

T2(int mem = 0) : mem(mem) { }

The original user defined constructor in the cpp reference example does absolutely nothing and still initializes mem . How? Is it just a rule I need to remember or is there something else happening?

Why does a user-provided constructor allow for instantiation of a const class instance?

Because the default constructor is responsible for initialisation of the object.

Sure, in this case the constructor fails to initialise the member in this case, but the compiler cannot generally know that whether it does that. Because a user defined constructor is used, it may make sense and thus there is no reason to disallow that.

The original user defined constructor in the cpp reference example does absolutely nothing and still initializes mem

It "default initialises" which is what happens when you don't initialise something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM