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

前端 未结 4 1990
粉色の甜心
粉色の甜心 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:31

    Since C++17, this code is correct, as is the similar code from this question:

    struct MyClass1 { int i{}; };
    struct MyClass2 { const MyClass1 m; };
    MyClass2 a;
    

    clang 8.0.0 rejects this latter code even with -std=c++17 which means that clang 8.0.0 has a bug.

    In C++17 the following new text was added as [dcl.init]/7 (as per P0490R0 in response to DR 253):

    A class type T is const-default-constructible if default-initialization of T would invoke a user-provided constructor of T (not inherited from a base class) or if

    • each direct non-variant non-static data member M of T has a default member initializer or, if M is of class type X (or array thereof), X is const-default-constructible,
    • if T is a union with at least one non-static data member, exactly one variant member has a default member initializer,
    • if T is not a union, for each anonymous union member with at least one non-static data member, exactly one non-static data member has a default member initializer, and
    • each potentially constructed base class of T is const-default-constructible.

    If a program calls for the default-initialization of an object of a const-qualified type T , T shall be a const-default-constructible class type or array thereof.


    Prior to C++17 there was no such text; an object defined as const must either have an initializer or a user-provided constructor. So, prior to C++17, clang was correct and g++ was bugged to accept the code without diagnostic.

提交回复
热议问题