C++11 introduced the ability to mark member functions as deleted, which means that any attempt to call those functions causes a compilation error. This can be used to prevent improper usage of a class. For example, if a class is meant to manage a unique resource, an object of that class shouldn't be copiable. This can be achieved by deleting its copy constructor and copy assignment functions.
With C++11 the delete
keyword can be used to explicitly forbid the usage of a member function: if it is deleted, any attempt to call it will cause a compilation error (there is no difference at runtime). This is useful when calling that function could lead to wrong results and/or unexpected behaviour.
An example is a class that has to manage a unique resource: an object of that class must not be copiable. Normally, to ensure that a function is not used, a programmer must simply avoid declaring it. But in some cases it is not enough, because some functions can be automatically generated by the compiler even though the programmer hasn't declared them. These functions include constructors, copy/move constructors and copy/move assignments. Not defining them doesn't guarantee that they can't be used. The solution is to use the = delete;
syntax.
For example, the following class declares a constructor and a destructor, but deletes the copy constructor and copy assignment:
class Unique_manager {
Unique_manager(); // Constructor
~Unique_manager(); // Destructor
Unique_manager(const Unique_manager&) = delete; // Forbid copy constructor
Unique_manager& operator=(const Unique_manager&) = delete; // Forbid copy assignment
};
In this case it would be possible to create an object of this class:
Unique_manager db_access_manager;
but an attempt to create a copy from it would be blocked by the compiler:
Unique_manager another_db_manager(db_access_manager); // Error: copy constructor
Unique_manager one_more_access_manager; // OK: constructor
one_more_access_manager = db_access_manager; // Error: copy assignment