简体   繁体   中英

When are C++ default constructors implicitly deleted?

Referencing cppreference.com ,

If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

If some user-declared constructors are present, the user may still force the automatic generation of a default constructor by the compiler that would be implicitly-declared otherwise with the keyword default.

This tells me when a default constructor for my class is declared (either by myself or by the compiler).

This does not tell me when there is guaranteed no default constructor. My reading of that article leaves open the possibility that the compiler could provide a default constructor anyways. Hence the existence of a default constructor might be implementation-dependent.

For example, according to my reading of the article, a default constructor might still be declared even if I provide a user-defined constructor (with arguments).

Question: when are default constructors guaranteed to be not defined? Is there any grey area where that is implementation-dependent?

I appreciate some sort-of-official reference on this. The standard says:

A default constructor for a class X is a constructor of class X for which each parameter that is not a function parameter pack has a default argument (including the case of a constructor with no parameters). If there is no user-declared constructor for class X, a non-explicit constructor having no parameters is implicitly declared as defaulted (11.4). An implicitly-declared default constructor is an inline public member of its class.

In my reading, this leaves open the possibility that I declare a constructor but the compiler may or may not declare a default constructor.

class Foo { 
public:
// Is this one already declared?
// Foo();
Foo( int i );
}

As pointed out in the comments, and in the edit to your question, this Draft C++17 Standard has the following:

15.1 Constructors [class.ctor]



4 … If there is no user-declared constructor for class X, a non-explicit constructor having no parameters is implicitly declared as defaulted.

I'm not sure how you interpret this as, in any way, ambiguous. We could express this in 'pseudo' C++ code as follows:

bool user-declared_ctor;
//...
if (!user-declared_ctor) {
    Make_Implicit_Def_Ctor();
}
else {
    // Don't!
}

Or would you prefer that the keyword in C++ were renamed to ?关键字重命名为

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM