Defaulted and Deleted Functions

ISO/IEC JTC1 SC22 WG21 N2346 = 07-0206 - 2007-07-19

Lawrence Crowl, Lawrence@Crowl.org, crowl@google.com

This document is a revision of N2326 = 07-0186 - 2007-06-22.

Overview

We propose a syntax and semantics for explicitly using the default definition of a function. We also propose a syntax and semantics for deleting the definition of an otherwise visible function.

Problem Description

By default, C++ provides four default special member functions:

Users may override these defaults.

Also by default, C++ applies several global operators to classes:

Users may provide class-specific operators.

The management of defaults has several problems:

The most common encounter with these problems is when disabling copying of a class. The accepted technique is to declare a private copy constructor and a private copy assignment operator, and then fail to define either. Unfortunately, the type becomes non-POD and its default constructor must be explicitly written. Further, while diagnostics for non-friend uses are relatively straightforward, the diagnostics for friend uses are deferred to link time and a cryptic a missing symbol message.

The specific problem of concisely ensuring that a class is non-copyable has received attention from Boost. See the documentation and header for the boost::noncopyable mixin. This mixin works, though not with entirely satisfactory results. First, the mechanism uses a base class, which under the current language makes the class non-POD. Second, the error messages can be somewhat misleading.

Any successful solution to these problems must be relatively easy to learn and implement.

Prior Approaches

The problems of defaults has been addressed via four primary approaches, as described below. These approaches have significant overlap, but none provide all of the capabilities of any of the others.

Class Scope Using Declarations and Private Members

In N1602 Class Scope Using Declarations & private Members, Francis Glassborow notes that some programmers make problematic overloads private members to prevent their use. This approach makes using valid overloads in derived classes an error, thus inhibiting the technique. He proposes defering the error diagnostic to the point where a private overload is selected in a call.

Explicit Classes and Default Definitions

In N1717 explicit class and default definitions, Francis Glassborow and Lois Goldthwaite define syntax to indicate that a class has none of the four default special member functions and then to explicitly resurrect the desired defaults. The paper proposed no change to the default application of global operators.

The explicit class approach has a significant syntactic burden for removing a single special member function -- remove them all and rewrite the declarations for the others. This approach encourages a view that explicit classes are inherently different, rather than a restriction of regular classes.

The paper states that

Special member functions which have been explicitly declared and default-defined are never trivial. Therefore an explicit class can never be a POD, even if its special member functions are default-defined. (The justification for this restriction is that the semantics of a class should not change if its inline default-defined functions are moved out of line.)
However, this is too much of a restriction. An inline default-defined function should be trivial if and only if the implicit definition would be trivial. Of course, non-inline definitions should be non-trivial. In essence, we agree with the justification, but not the restriction. Fortunately, subsequent work on the definition of PODs by Beman Dawes in N2294 POD's Revisited; Resolving Core Issue 568 (Revision 4)) provides tools to revisit this issue.

The syntax suggested in N1717 for explicit defaults permits simultaneous specification of a member initializer list, which is clearly not right. Rather than add additional restrictive text, a restrictive syntax is preferable.

The paper left incomplete the specification that an explicit class without a copy constructor is deemed to have an inaccessible copy constructor. This specification was intended to avoid reverse slicing, where only a sub-object is initialized. The situation is similar for copy assignment operators.

List of Class Defaults

In N1890 Initialization and Initializers section 7, as elaborated in the draft Control of class defaults, Bjarne Stroustrup describes a syntax for controlling defaults, with more goals than N1717. These goals include not only controlling member defaults, but also controlling the application of global operators, other possible default implementations, and control of inheritance.

The paper's proposed syntax is very terse, and requires a mental mapping from the short codes of the default control list to the actual functions. For the most part, this mapping is straightforward, but still must be memorized. Further, its different syntactic style will slow adoption by users and compiler vendors.

In contrast to N1717, the paper provides no mechanism to define a non-inline member using the default definition.

The paper also includes mechanisms for controlling class defaults, which essentially involve inheritance.

In the current language: The paper addresses these inheritance issues as well.

Prohibited Access Specifier

In N2123 Adding the prohibited access specifier to C++09 Alisdair Meredith describes a prohibited access specifier that disables undesired operations within classes. This notion was first introduced by Daveed Vandevoorde in N1964 Modules in C++ (revision 3).

The proposal also enables defining prohibited conversions via declaration of a prohibited overload. This aspect of the proposal is probably the most significant, as it extends into user-defined operations and addresses a major weakness in C++, agressive conversion.

The technique works because the prohibited functions are still visible. Syntactically, the specifier also applies to other data members, for which it does not make sense and requires additional rules. A more precise mechanism is desirable.

Furthermore, the access specifier does not work for free functions. This missing feature seems like such an obvious next step that its absence will be felt.

The prohibited keyword is new, which will break some programs. A Google code search yields about 500 hits. Sensibly reusing an existing keyword will not affect existing programs.

Unlike N1717, the paper does not propose a means to specify non-inline default implementations. Unlike N1890, the paper does not propose a means to specify default implementations for functions that have no implicit default.

Proposed Solution

We propose to define two new mechanisms to explicitly use the default definition of a function and to delete a function definition. This solution

Syntactically, the proposal uses =default; and =delete; in alternate rules for function-definition. We considered the forms default;, as suggested by N1717, and {default}, as adopted by N1717, but chose not to use them. The reasons are that the former introduces more choice points into the parse of declarations, while the second introduces either more choice points in the parse of function blocks or substantial lookahead to determine that the syntax {default} is not a function block.

Default Function Definition

The definition form =default; indicates that the function's default definition should be used. As expected, this works when the definition is inside the class body, but it also works when the definition is outside the class body, but as with the current language, you must declare the function within the class body.


struct type
{
    type() = default; // commonly specified redundancy is now efficent
    virtual ~type(); // virtual requires a declaration
    type( const type & ); // a simple declaration, but
};
inline type::type( const type & ) = default; // now efficient
type::~type() = default; // a non-inline default definition

Trivial Definitions

Critical to exploiting the benefits of N2294, a explicitly-defaulted definition within its class is trivial if and only if the implicit definition would have been trivial.


struct type
{
    type() = default; // trivial
    virtual ~type() = default; // non-trivial because virtual
    type & operator =( const type & ); // non-trivial
    // because not defaulted here
};
inline type & type::operator =( const type & ) = default;

Non-inline definitions may also be defaulted.


struct type
{
    type( const type & ); // not defaulted here
};
type::type( const type & ) = default;

This rule enables efficient execution and concise definition while enabling a stable binary interface to an evolving implementation. That is, the machine-level calling sequence remains unchanged even when the definition changes to a non-default. For example, consider the header


type.h : struct type { int x; type(); };

and two (mutually exclusive) definitions as the software evolves,


type1.cc : type::type() = default;
type2.cc : type::type() { x = 3; }

In some cases, the class body can change without requiring a change in member function definition because the default changes with declaration of additional members.

Exception Specification

Unlike the implicit default, the explicit default has normal exception specification semantics. This inconsistency seems at the surface to be undesireable. The reason for the change in semantics is twofold. First, if the explicit default used the implicit exception specification, there would be no syntax to get back to a throws anything state. Second, the users of a function cannot tell if it is defaulted when it is non-inline, as in the example above. It would be undesirable to have semantics of use change due to a change in implementation. So, the explicit declaration needs to have the the normal exception semantics. Users desiring precisely the same exception specification as the implicit declaration must specify it. N1717 reached the same conclusion.

Non-Implicit Defaults

So far, this proposal has shown how to make explicit the implicit default definition. There is another opportunity, which is to use a default implementation that is not implicit. For example, consider the equality operator. There is no default equality operator, but an explicit default definition would be able to use a standard-defined, if not implicit, default definition.


struct type
{
    bool operator ==( const & type ) = default;
    bool operator !=( const & type ) = default;
};

Indeed, there are several potential operations that could have non-implicit default implementations. However, this paper proposes none. We believe that at this point in the standards process, such defaults are best left to a technical report. However, should such a technical report be forthcoming, the syntax is ready.

Delete Function Definition

The definition form =delete; indicates that the function may not be used. However, all lookup and overload resolution occurs before the deleted definition is noted. That is, it is the definition that is deleted, not the symbol; overloads that resolve to that definition are ill-formed.

The primary power of this approach is twofold. First, use of default language facilities can be made an error by deleting the definition of functions that they require. Second, problematic conversions can be made an error by deleting the definition for the offending conversion (or overloaded function).

This approach of checking for a delete definition late has two benefits. First, it achieves the goal of making a bad overload visible. Second, it is relativley easy to implement, requiring no change to the already complicated lookup and overload rules.

The deleted definition of a function must be its first declaration. This rule prevents inconsistency in interpretation.

The deleted definition is an inline definition, thus requiring consistent definition throughout the program via the one-definition rule.

The deleted definition mechanism is orthogonal to access specifiers, though accessibility is somewhat moot if the function has been deleted.

Deleted functions are trivial. This rule is necessary to obtain maximum benefit from N2294.

One can define a template with a deleted definition. Specialization and argument deduction occur as they would with a regular template function, but explicit specialization is not permitted.

One cannot use a deleted function in a sizeof expression. We believe the existing language rules will prevent this.

A deleted virtual function may not override a non-deleted virtual function and vice-versa.

Disabling Language Features

The canonical example of disabling language features is disabling copying. Simply declare the copy assignment operator and the copy constructor with deleted definitions. Because a declaration of any constructor disables the default constructor, a programmer may choose to add it back with its default definition.


struct type
{
    type & operator =( const type & ) = delete;
    type( const type & ) = delete;
    type() = default;
};

We avoid the problem of reverse slicing identified in N1717 because the declaration for a deleted definition still hides the base-class copy constructor.

A more subtle example involves indirectly controlling the allocation of a type. Deleting the definition of a class-specific operator new will prevent allocation in free store because new expressions involving type will be ill-formed.


struct type {
    void * operator new( std::size_t ) = delete;
};

In contrast, deleting the definition of a destructor will require allocation in free store because static and automatic variables implicitly call the destructor.


struct type {
    ~type() = delete; // disable destructor
};
Unfortunately, the approach also prevents deleting a free-store object, thus either limiting its use to singletons or requiring the employment of a garbage collector.

Disabling Undesired Conversions

Removing dangerous conversions is as important as removing undesired language defaults.


struct type
{
    type( long long ); // can initialize with an long long
    type( long ) = delete; // but not anything less
};
extern void bar( type, long long ); // and the same for bad overloads
void bar( type, long ) = delete; // of free functions

Of considerable note is the interaction of explicit constructors and explicit conversion operators with deleted definitions. (Lois Goldthwaite, Michael Wong, and Jens Maurer describe explicit conversion operators in N2333 Explicit Conversion Operator Draft Working Paper Revision 1.) The short answer is that the two facilities are orthogonal, explicit controls the set of functions considered and delete comments on the final choice. The more helpful answer is a bit more subtle. For example, consider


struct type
{
    type( long long );
    explicit type( long ) = delete;
};
extern void function( type );

Under this proposal, lookup and the semantics of explicit are unchanged, so in the overload resoultion for type(42), 42 promotes to long in the overload resolution, and a deleted function is selected, which is an error.


function( type( 42 ) ); // error 42 promotes to long
function( 42 ); // okay type(long long); type(long) not considered

In practice, explicit and delete will probably not be used together. Programmers desiring more restrictive diagnostics will use delete alone rather than explicit.

Comparison to Prior Approaches

Our solution provides all known strengths of N1602, N1717 and N2123 while avoiding many of the identified weakness. In particular, the explicit class qualifier and the prohibited access specifier would no longer be necessary.

The solution addresses most of the goals of N1890(7), specifically those related to function definitions, but not those related to class defaults of inheritance. We have chosen not to address class defaults for the following reasons.

Our proposed syntax is more tedious than that of N1890(7), but also more general, applying to user-defined member and free functions as well.

Use Case - Atomic Types

Paper N2145 C++ Atomic Types and Operations described a failure to achieve desired semantics for atomic types with with C++ 2003. With this proposal and others, an effective and correct definition is defined in N2324 C++ Atomic Types and Operations and thus is a motivating use case for the proposal.

The following code, as defined in this proposal and in conjunction with N2215 Initializer lists (Rev.3), N2294 POD's Revisited; Resolving Core Issue 568 (Revison 4), and N2235 Generalized Constant Expressions — Revision 5, appears to satisfy the requirements of N2145.


typedef struct atomic_int
{
#ifdef __cplusplus
    // destructor implicitly declared and defined
    atomic_int() = default; // otherwise suppressed by other constructors
    constexpr atomic_int( int v ) : f ( v ) { } // construct from value
    int operator =( int v ) volatile; // assign from value
    atomic_int( const atomic_int & ) = delete; // too dangerous
    atomic_int & operator =( const atomic_int & ) = delete; // also
    operator int(); // load the value
private:
#endif
    int f;
} atomic_int;

The destructor is implicitly-defaulted and trivial. The default constructor is explicitly-defaulted and trivial. The copy constructor and copy assignment operators are deleted and therefore trivial.

N2235 and the constexpr value constructor together permit static initialization. N2215 permits aggregate initialization syntax.

The erroneous defaults for copying are deleted, preventing their use. One can still copy from one atomic to another, but only going through a non-atomic value, which makes clear that a copy between two atomics is not itself atomic.


atomic_int w = { 3 }; // static initialization
atomic_int x; // default zero initialization
void function( atomic_int * p ) {
    atomic_int y( *p ); // error copy constructor is deleted
    atomic_int z( int(*p) ); // okay copy construct through value
    *p = x; // error copy assignment is deleted
    *p = int(x); // okay copy assignment through value
}

Changes to the Standard

We propose the following changes to the standard. The base document is N2315 Working Draft, Standard for Programming Language C++.

5.3.4 New [expr.new]

Within paragraph 16, edit

A new-expression that creates an object of type T initializes that object as follows:

8.4 Function definitions [dcl.fct.def]

In paragraph 1, edit

Function definitions have the form
function-definition:
decl-specifier-seqopt declarator ctor-initializeropt function-body
decl-specifier-seqopt declarator function-try-block
decl-specifier-seqopt declarator  = default ;
decl-specifier-seqopt declarator  = delete ;

Add a new paragraph 7.

A function definition of the form:
decl-specifier-seqopt declarator = default ;
is called an explicitly-defaulted definition. Only special member functions may be explicitly defaulted, and the implementation will define them as if they had implicit definitions (12.1, 12.4, 12.8). A special member function is user-provided if it is user-declared and not explicitly defaulted on its first declaration. A user-provided explicitly-defaulted function is defined at the point where it is explicitly defaulted. [ Note: While an implicitly-declared special member function is inline (clause 12), an explicitly-defaulted definition may be non-inline. Non-inline definitions are user-provided, and hence non-trivial (12.1, 12.4, 12.8). This rule enables efficient execution and concise definition while enabling a stable binary interface to an evolving codebase. — end note ] [ Example:

struct trivial {
    trivial() = default;
    trivial( const trivial & ) = default;
    trivial & operator =( const trivial & ) = default;
    ~trivial() = default;
};

struct nontrivial1 {
    nontrivial1();
};
nontrivial1::nontrivial1() = default; // not inline

struct nontrivial2 {
    nontrivial2();
};
inline nontrivial2::nontrivial2() = default; // not first declaration

struct nontrivial3 {
    virtual ~nontrivial3() = 0; // virtual
};
inline nontrivial3::~nontrivial3() = default; // not first declaration
end example ]

Add a new paragraph 8.

A function definition of of the form:
decl-specifier-seqopt declarator = delete ;
is called a deleted definition. A function with a deleted definition is also called a deleted function. A deleted definition of a function shall be the first declaration of the function. [ Example:

struct sometype {
    sometype();
};
sometype::sometype() = delete; // ill-formed; not first declaration
end example ] A deleted function is implicitly inline. [ Note: The one-definition rule (3.2 [basic.def.odr]) applies to deleted definitions. — end note ] A program that refers to a deleted function implicitly or explicitly, other than to declare it, is ill-formed. [ Note: This includes calling the function explicitly or implicitly and forming a pointer or pointer-to-member to the function. It applies even for references in expressions that are not potentially-evaluated. If a function is overloaded, it is referenced only if the function is selected by overload resolution. — end note ] [ Example: One can enforce non-default initialization and non-integral initialization with

struct sometype {
    sometype() = delete ; // redundant, but legal
    sometype( std::intmax_t ) = delete;
    sometype( double );
};
end example ] [ Example: One can prevent use of a class in certain new expressions by using deleted definitions of a user-declared operator new for that class.

struct sometype {
    void * operator new( std::size_t ) = delete;
    void * operator new[]( std::size_t ) = delete;
};
sometype * p = new sometype; // error, deleted class operator new
sometype * p = new sometype[3]; // error, deleted class operator new[]
end example ]

8.5 Initializers [dcl.init]

Within paragraph 5, edit

To value-initialize an object of type T means:

In paragraph 9, edit

If no initializer is specified for an object, and the object is of (possibly cv-qualified) non-POD class type (or array thereof), the object shall be default-initialized; if the object is of const-qualified type, the underlying class type shall have a user-declared user-provided default constructor. Otherwise, if no initializer is specified for a non-static object, the object and its subobjects, if any, have an indeterminate initial value92); if the object or any of its subobjects are of const-qualified type, the program is ill-formed.

8.5.1 Aggregates [dcl.init.aggr]

In paragraph 1, edit

An aggregate is an array or a class (clause 9) with no user-declared user-provided constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10), and no virtual functions (10.3).

In paragraph 13, edit

[ Note: An aggregate array or an aggregate class may contain members of a class type with a user-declared user-provided constructor (12.1). Initialization of these aggregate objects is described in 12.6.1. — end note ]

9 Classes [class]

In paragraph 4, edit

A union is a class defined with the class-key union; it holds only one data member at a time (9.5). [ Note: aggregates of class type are described in 8.5.1. — end note ] A POD class is an aggregate class that has no non-static data members of non-POD type (or array of such a type) or reference, and has no user-declared user-provided copy assignment operator and no user-declared user-provided destructor. A POD-struct is a POD class defined with the class-key struct or the class-key class. A POD-union is a POD class defined with the class-key union.

9.2 Class members [class.mem]

Paragraph 14, unchanged.

In addition, if class T has a user-declared constructor (12.1), every non-static data member of class T shall have a name different from T.

10.3 Virtual functions [class.virtual]

At the end of the section, add a new paragraph

A function with a deleted definition ([dcl.fct.def]) shall not override a function that does not have a deleted definition. Likewise, a function that does not have a deleted definition shall not override a function with a deleted definition.

12.1 Constructors [class.ctor]

Within paragraph 5, edit

A default constructor is trivial if it is implicitly-declared not user-provided (8.4 [dcl.fct.def]) and if:

In paragraph 7, edit

An implicitly-declared non-user-provided default constructor for a class is implicitly defined when it is used (3.2) to create an object of its class type (1.8). The implicitly-defined or explicitly-defaulted default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with an empty mem-initializer-list (12.6.2) and an empty function body. If that user-written default constructor would be ill-formed, the program is ill-formed. Before the implicitly-declared non-user-provided default constructor for a class is implicitly defined, all the implicitly-declared non-user-provided default constructors for its base classes and its non-static data members shall have been implicitly defined. [ Note: an implicitly-declared default constructor has an exception-specification (15.4). An explicitly-defaulted definition has no implicit exception-specification.end note ]

12.4 Destructors [class.dtor]

Within paragraph 3, edit

If a class has no user-declared destructor, a destructor is declared implicitly. An implicitly-declared destructor is an inline public member of its class. A destructor is trivial if it is implicitly-declared not user-provided (8.4 [dcl.fct.def]) and if:

In paragraph 5, edit

An implicitly-declared non-user-provided destructor is implicitly defined when it is used to destroy an object of its class type (3.7). A program is ill-formed if the class for which a destructor is implicitly defined or explicitly defaulted has: Before the implicitly-declared non-user-provided destructor for a class is implicitly defined, all the implicitly-declared non-user-provided destructors for its base classes and its non-static data members shall have been implicitly defined. [ Note: an implicitly-declared destructor has an exception-specification (15.4). An explicitly-defaulted definition has no implicit exception-specification.end note ]

12.6.2 Initializing bases and members [class.base.init]

Within paragraph 4, edit

If a given non-static data member or base class is not named by a mem-initializer-id (including the case where there is no mem-initializer-list because the constructor has no ctor-initializer), then

12.8 Copying class objects [class.copy]

In paragraph 4, no change.

If the class definition does not explicitly declare a copy constructor, one is declared implicitly. Thus, for the class definition

struct X {
    X(const X&, int);
};
a copy constructor is implicitly-declared. If the user-declared constructor is later defined as

X::X(const X& x, int i =0) { /* ... */ }
then any use of X’s copy constructor is ill-formed because of the ambiguity; no diagnostic is required.

Within paragraph 6, edit

A copy constructor for class X is trivial if it is implicitly declared not user-provided (8.4 [dcl.fct.def]) and if

In paragraph 7, edit

An implicitly-declared non-user-provided copy constructor is implicitly defined if it is used to initialize an object of its class type from a copy of an object of its class type or of a class type derived from its class type108). [ Note: the copy constructor is implicitly defined even if the implementation elided its use (12.2). — end note ] A program is ill-formed if the class for which a copy constructor is implicitly defined, or explictly defaulted, has: Before the implicitly-declared non-user-provided copy constructor for a class is implicitly defined, all implicitly-declared non-user-provided copy constructors for its direct and virtual base classes and its non-static data members shall have been implicitly defined. [ Note: an implicitly-declared copy constructor has an exception-specification (15.4). An explicitly-defaulted definition has no implicit exception-specification.end note ]

Within paragraph 8, edit

The implicitly-defined or explicitly-defaulted copy constructor for class X performs a memberwise copy of its subobjects.

Within paragraph 9, unchanged.

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.109)

Within paragraph 11, edit

A copy assignment operator for class X is trivial if it is implicitly declared not user-provided and if

In paragraph 12, edit

An implicitly-declared non-user-provided copy assignment operator is implicitly defined when an object of its class type is assigned a value of its class type or a value of a class type derived from its class type. A program is ill-formed if the class for which a copy assignment operator is implicitly defined or explicitly defaulted, has: Before the implicitly-declared non-user-provided copy assignment operator for a class is implicitly defined, all implicitly-declared non-user-provided copy assignment operators for its direct base classes and its non-static data members shall have been implicitly defined. [ Note: an implicitly-declared copy assignment operator has an exception-specification (15.4). An explicitly-defaulted definition has no implicit exception-specification.end note ]

Within paragraph 13, edit

The implicitly-defined or explicitly-defaulted copy assignment operator for class X performs memberwise assignment of its subobjects. .... it It is unspecified whether subobjects representing virtual base classes are assigned more than once by the implicitly-defined or explicitly-defaulted copy assignment operator.

14.7.3 Explicit specialization [temp.expl.spec]

In paragraph 1, edit

An explicit specialization of any of the following: can be declared by a declaration introduced by template<>;

C.1.8 Clause 12: special member functions [diff.special]

In paragraph 1, edit

12.8 (copying class objects)
Change:
The implicitly-declared copy constructor and implicitly-declared copy assignment operator cannot make a copy of a volatile lvalue. For example, the following is valid in ISO C:

struct X { int i; };
struct X x1, x2;
volatile struct X x3 = {0};
x1 = x3; // invalid C++
x2 = x3; // also invalid C++
Rationale:
Several alternatives were debated at length. Changing the parameter to volatile const X& would greatly complicate the generation of efficient code for class objects. Discussion of providing two alternative signatures for these implicitly-defined operations raised unanswered concerns about creating ambiguities and complicating the rules that specify the formation of these operators according to the bases and members.
Effect on original feature:
Deletion of semantically well-defined feature.
Difficulty of converting:
Semantic transformation. If volatile semantics are required for the copy, a user-declared constructor or assignment must be provided. [ Note: This user-declared constructor may be explicitly defaulted. — end note ] If non-volatile semantics are required, an explicit const_cast can be used.
How widely used:
Seldom.