gpt4 book ai didi

删除构造函数的 C++14 值初始化

转载 作者:IT老高 更新时间:2023-10-28 12:30:05 28 4
gpt4 key购买 nike

我有一些误解:

让我们将结构 A 的默认构造函数标记为已删除:

struct A
{
A() = delete;
};

下一条指令格式正确,效果如何?:

A a{};

来自 cppreference value initilization :

1) If T is a class type with no default constructor or with a user-provided default constructor or with a deleted default constructor, the object is default-initialized.

但是那么默认初始化的效果是:

If T is a class type, the default constructor is called to provide the initial value for the new object.

还是聚合初始化?谢谢!

最佳答案

你的 struct A 是:

  • 一个类类型,它具有:
    • 没有用户提供的构造函数1,
    • 没有私有(private)或 protected 非静态数据成员,
    • 没有基类,
    • 没有虚拟成员函数。

因此,根据 § 8.5.1/1 提供的定义,它可以作为一个聚合类型

然后是聚合初始化优先于值初始化。该标准规定聚合初始化优先于值初始化(草案 N3936,第 8.5.4/3 节,第 201 页)(强调我的)

List-initialization of an object or reference of type T is defined as follows:

  • If T is an aggregate, aggregate initialization is performed (8.5.1).
  • Otherwise, if the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
  • [... more rules...]

(1) 根据评论中关于为什么删除的构造函数不计为用户定义的要求,以下是标准说(草案 N3936,第 8.4.2/5 节,第 198 页):

A function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration.

关于删除构造函数的 C++14 值初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23882409/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com