删除构造函数的C ++ 14值初始化 [英] C++14 value-initialization with deleted constructor

查看:245
本文介绍了删除构造函数的C ++ 14值初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些误解:



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

  struct A 
{
A()= delete;
};

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

  A a {}; 

cppreference 值初始化


1)如果T是类类型没有默认构造函数或者用
用户提供的默认构造函数或者删除默认的
构造函数,对象是默认初始化的。


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


如果T是类类型,默认构造函数被调用为新对象提供
初始值。


还是聚合初始化?
谢谢!

解决方案

您的 struct A / p>


  • 一个类类型包含:

    • 没有用户提供的构造函数 1
    • 没有私人或受保护的非静态资料成员,

    • 没有基类,

    • 没有虚拟成员函数。




聚合类型,根据第8.5.1 / 1节提供的定义。



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


类型T的对象或引用的列表初始化定义如下:




  • 如果T是聚合,

  • 否则,如果初始化器列表没有元素,T是具有默认构造函数的类类型,则对象将被初始化。

  • [...更多规则...]


(1) 根据为什么已删除的构造函数不会计为用户定义的注释中的要求, (N3936草案,第8.4.2 / 5页,第198页):


如果用户声明函数,未在其第一个声明中显式默认或删除。



I have some misunderstanding:

Let's mark default constructor of struct A as deleted:

struct A
{
  A() = delete;
};

The next instruction is well-formed and what's that effect?:

A a{};

From 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.

but then the effect of default initialization is:

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

Or it's aggregate initialization? Thanks!

解决方案

Your struct A is :

  • a class type that has:
    • no user-provided constructors1,
    • no private or protected non-static data members,
    • no base classes,
    • no virtual member functions.

It therefore qualifies as an aggregate type, according to the definition provided by § 8.5.1/1.

Then comes the priority of aggregate initialization over value initialization. The standard says that aggregate initialization has precedence over value intialization (draft N3936, § 8.5.4/3, page 201) (emphasis mine)

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) As requested in the comments on why a deleted constructor does not count as user-defined, here is what the standard says (draft N3936, § 8.4.2/5, page 198):

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

这篇关于删除构造函数的C ++ 14值初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆