Do I really need to implement user-provided constructor for const objects?

前端 未结 4 1991
粉色の甜心
粉色の甜心 2020-11-27 18:45

I have the code:

class A {
  public:
    A() = default;

  private:
    int i = 1;
};

int main() {
  const A a;
  return 0;
}

It compiles

4条回答
  •  死守一世寂寞
    2020-11-27 19:25

    Note that you can turn your class easily into one which has a user-defined default constructor:

    class A {
      public:
        A();
    
      private:
        int i = 1;
    };
    
    inline A::A() = default;
    

    According to 8.4.2 [dcl.fct.def.default] paragraph 4:

    ... A special member function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. ...

    This implicitly states that a function which is not explicitly defaulted on its first declaration is not user-provided. In combination with 8.5 [dcl.init] paragraph 6

    ... If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

    it seems clear that you cannot use a default constructor defaulted on its first declaration to initialize a const object. However, you can use a defaulted definition if it isn't the first declaration as is done in the code above.

提交回复
热议问题