加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 05:17:52 所属栏目:百科 来源:网络整理
导读:从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 ; 但由于该类类型已删除默认构造函数,该对象如何进行默认初始化?
从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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读