简体   繁体   English

已删除的析构函数是否会更改 C++ 中的聚合初始化?

[英]Does deleted destructor change aggregate initialization in C++?

The code as follows代码如下

struct B {
    ~B() = delete;
};

B * b = new B{};

fails to compile in the latest MSVC with the error:无法在最新的 MSVC 中编译并出现以下错误:

error C2512: 'B': no appropriate default constructor available
note: Invalid aggregate initialization

At the same time both GCC and Clang do not see anything wrong in the code, demo: https://gcc.godbolt.org/z/va9vcsEed同时GCC和Clang都看不出代码有什么问题,demo: https://gcc.godbolt.org/z/va

Is it right to assume just a bug in MSVC?假设只是 MSVC 中的一个错误是否正确?

Overall, does the presence or deletion of the destructor change any rule of the aggregate initialization?总的来说,析构函数的存在或删除是否会改变聚合初始化的任何规则?

Neither definition of the notion of aggregate in C++ Standards refers to the destructor. C++ 标准中聚合概念的定义都没有提到析构函数。

For example the definition of an aggregate in C++ 20 (9.4.2 Aggregates) sounds the following way例如,C++ 20 (9.4.2 Aggregates) 中聚合的定义听起来如下

1 An aggregate is an array or a class (Clause 11) with 1 聚合是一个数组或一个 class(第 11 条)

(1.1) — no user-declared or inherited constructors (11.4.5), (1.1) — 没有用户声明或继承的构造函数 (11.4.5),

(1.2) — no private or protected direct non-static data members (11.9), (1.2) — 没有私有或受保护的直接非静态数据成员 (11.9),

(1.3) — no virtual functions (11.7.3), and (1.3) — 没有虚函数 (11.7.3),和

(1.4) — no virtual, private, or protected base classes (11.7.2). (1.4) — 没有虚拟、私有或受保护的基类 (11.7.2)。

If to execute this statement in MS VS 2019如果在 MS VS 2019 中执行此语句

std::cout << std::is_aggregate_v<B> << '\n';

then the output will be 1 .那么 output 将为1

On the other hand, the default constructor is defined as deleted (the C++ 20 Standard, 11.4.5.2 Default constructors) if另一方面,默认构造函数定义为已删除(C++ 20 标准,11.4.5.2 默认构造函数)如果

(2.8) — any potentially constructed subobject has a type with a destructor that is deleted or inaccessible from the defaulted default constructor. (2.8) — 任何可能构造的子对象都具有带有析构函数的类型,该析构函数已从默认的默认构造函数中删除或不可访问。

But in the provided example there is no such sub-object.但是在提供的示例中没有这样的子对象。

So it seems it is a compiler bug of MS VS 2019.所以它似乎是 MS VS 2019 的编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM