3

Here's the code example in question:

struct A {
    A() = delete;
};

int main()
{
//  A a(); // compiles, since it's a function declaration (most vexing parse)
//  A a;   // does not compile, just as expected
    A a{}; // compiles, why? The default constructor is deleted.
}

Try it here with any of the available compilers. I tried with several and didn't find one that gave a compilation error.

Leo Heinsaar
  • 3,887
  • 3
  • 15
  • 35
  • There was such question already, check this: [Deleted default constructor. Objects can still be created… sometimes](https://stackoverflow.com/questions/33988297/deleted-default-constructor-objects-can-still-be-created-sometimes). – Michał Kalinowski Jul 27 '18 at 11:07
  • Thanks for pointing out that it's a duplicate. I wouldn't want to delete it though since it's a more concise version — I forwarded this question here because neither I nor the person who asked me could find the linked original. – Leo Heinsaar Jul 27 '18 at 11:22

2 Answers2

5

This is a current language issue that is very likely to be fixed soon. The proposal that tackles the necessary design change can be found here. From the abstract of the proposal:

C++ currently allows some types with user-declared constructors to be initialized via aggregate initialization, bypassing those constructors. The result is code that is surprising, confusing, and buggy

lubgr
  • 37,368
  • 3
  • 66
  • 117
2

Because A is an aggregate type, then given A a{}; aggregate initialization is performed.

Each direct public base, (since C++17) array element, or non-static class member, in order of array subscript/appearance in the class definition, is copy-initialized from the corresponding clause of the initializer list.

In aggregate initialization, every member or element (if any) will be copy-initialized directly, the constructor is bypassed; so it's deleteed or not doesn't matter.

Note that explicitly deleted constructors are allowed for aggregate types (since C++11) (until C++20),

no user-provided constructors (explicitly defaulted or deleted constructors are allowed) (since C++11) (until C++17)

no user-provided, inherited, or explicit constructors (explicitly defaulted or deleted constructors are allowed) (since C++17) (until C++20)

Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405