问题
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.
回答1:
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
回答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 delete
ed 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)
来源:https://stackoverflow.com/questions/51556595/why-does-a-a-compile-when-the-default-constructor-aa-is-deleted