Understanding the Meaning of "= delete" in Function Declarations
In C 11, the "= delete" syntax is used to delete a function, effectively preventing its use. It is commonly employed to prohibit copying or to restrict certain conversions.
Deleting Copy Constructors and Assignment Operators
Perhaps the most common use case for "= delete" is to disallow copying. For instance, if we have a class called "my_class" that we do not want to be copied, we can declare:
class my_class { public: ... my_class(const my_class &) = delete; ... };
This declaration prevents the compiler from generating a default copy constructor and assignment operator for "my_class."
Preventing Undesirable Conversions
Another use of "= delete" is to prohibit specific type conversions. For example, if we have a class "Z" that we want to be constructed only from "long long" values, we can use "= delete" to prevent conversions from smaller types:
struct Z { public: ... Z(long long); // can initialize with a long long Z(long) = delete; // but not anything less };
Additional Function Modifiers
Besides "= 0" (which sets the function to pure virtual) and "= delete" (which deletes the function), there are no other function modifiers in C . However, other keywords such as "override" and "final" can be used to modify the behavior of virtual functions.
The above is the detailed content of What does '= delete' mean in C function declarations?. For more information, please follow other related articles on the PHP Chinese website!