Why does 'A a{};' compile when the default constructor A::A() is deleted? [duplicate]

半城伤御伤魂 提交于 2020-06-23 07:41:21

问题


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 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)



来源:https://stackoverflow.com/questions/51556595/why-does-a-a-compile-when-the-default-constructor-aa-is-deleted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!