Could a class type with deleted default constructor be default initialized?

  • A+
Category:Languages

From what cppref says about 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;

But since that class type has deleted default constructor, how could the object be default-initialized?

As far as I know, default initialization of class type needs the access of default constructor. If we have:

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

Then A *a = new A; will fail, so does A* a = new A();.

But A a{}; is OK. But why? According to cppreference

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


I think the standard just means "if T is a class type with deleted default constructor then goto default initialization". It would fail at last because the constructor selected for default initialization is deleted. It's used to distinguish with the 2nd case, i.e. "if T is a class type with a default constructor that is neither user-provided nor deleted", for that case zero-initialization is performed firstly, then default-initialization if T has a non-trivial default constructor.

A a{} is OK,but why?

Because when A is an aggregate type aggregate initialization is performed. Note that explicitly deleted constructors are allowed for aggregate type since 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.

And

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)

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: