c – 是否可以默认初始化具有已删除默认构造函数的类类型?

前端之家收集整理的这篇文章主要介绍了c – 是否可以默认初始化具有已删除默认构造函数的类类型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
从cppref所说的约 value initialization

if T is a class type with no default constructor or with a user-provided or deleted default constructor,the object is default-initialized;

但由于该类类型已删除默认构造函数,该对象如何进行默认初始化?

据我所知,类类型的默认初始化需要访问默认构造函数.如果我们有:

struct A {
    A() = delete;
    int k;
};

然后A * a =新A;会失败,A * a = new A();也是如此.

但是A a {};没关系但为什么?根据cppreference

Otherwise,If the braced-init-list is empty and T is a class type with a default constructor,value-initialization is performed.

解决方法

我认为标准只是意味着“如果T是带有删除的默认构造函数的类类型,那么转到默认初始化”.它最终会失败,因为删除了为默认初始化选择的构造函数.它用于区分第二种情况,即“如果T是具有默认构造函数的类型,既不是用户提供也不是删除”,对于这种情况,首先执行零初始化,然后如果T具有非默认初始化-trivial默认构造函数.

A a{} is OK,but why?

因为当A是aggregate type聚合时,执行初始化.请注意,自C 11起,允许显式删除的构造函数用于聚合类型.

In all cases,if the empty pair of braces {} is used and T is an aggregate type,aggregate-initialization is performed instead of value-initialization.

An aggregate is one of the following types:

  • array type
  • class type (typically,struct or union),that has
    • no private or protected non-static data members
    • no user-provided,inherited,or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)
原文链接:https://www.f2er.com/c/115048.html

猜你在找的C&C++相关文章