Deleted functions in C++11
FangLu 2700058AGP Comment (1) Visits (59313)
The deleted functions feature is introduced into the C++11 standard. In this article, I will explain this feature and provide some examples on how to use it.
C++ has six kinds of special member functions:
•Copy assignment operators
•Move assignment operators
These special member functions are used to create, destroy, initialize, convert, and copy class objects.
Suppose that you haven't defined a certain special member function for a class; when such a special member function is needed, the compiler will implicitly declare a default special member function for this class. For example:
X x2=x1; // Fine. A default copy constructor is implicitly
x3=x1; // Fine. A default copy assignment operator is
In this example, there is no user-defined copy constructor or copy assignment operator. However, when these two special member functions are needed, the compiler will implicitly declare a default copy constructor and a copy assignment operator.
In some cases, having the compiler define special member functions implicitly can benefit programmers:
•Programmers need not to manually define these special member functions. The manual definition requires more coding effort.
•The compiler implicitly defined member functions are more efficient than the user-defined special member functions.
However, it might become a problem if you want to forbid copy or assignment operations between class objects. but you cannot stop the compiler from defining the default copy constructor or copy assignment operator implicitly.
To address this problem, C++11 introduced the deleted functions feature.
The C++11 standard introduced deleted function declaration as a new form of function declaration.
To declare a deleted function, you can append the “=delete;” specifier to the end of a function declaration. The compiler prohibits the usage of a deleted function. For example, you can declare the implicitly defined copy constructor and copy assignment operator of class X as deleted functions to prevent object copy of that class.
X(const X&) = dele
X& operator = (const X &) = dele
X x2=x1; //Error. The usage of the copy constructor is disabled.
x3=x1; //Error. The usage of the copy assignment operator is disabled.
In example 2, although only one copy constructor and one copy assignment operator are declared as deleted functions explicitly, the compiler can detect the declarations of the user-defined copy constructor and copy assignment operator. Thus, the compiler will no longer implicitly define any other copy constructors or copy assignment operators that have different parameters. In this case, the copy and assign operations between class objects are totally prohibited.