Is the following enough (from a best-practice perspective) for a nonmovable type?
class A
{
A(const A&) = delete;
A(A&&) = delete;
A& operator=(A) = delete;
public:
A();
};
Or do I have to delete the copy/move assignment operators separately? Also is a destructor required here?
Explanation: The delete operator is the reverse process of a new operator. It deallocates all the memory allocated for an object. The object can be of any type. The delete operator completely destroys an object so that the resources can be used for other purposes.
Deleted function declaration is a new form of function declaration that is introduced into the C++11 standard. To declare a function as a deleted function, you can append the =delete; specifier to the end of that function declaration. The compiler disables the usage of a deleted function.
When to delete copy constructor and assignment operator? Copy constructor (and assignment) should be defined when ever the implicitly generated one violates any class invariant. It should be defined as deleted when it cannot be written in a way that wouldn't have undesirable or surprising behaviour.
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .
Yes, declaring the copy constructor and copy assignment operators as deleted
is enough. Since you are declaring a copy constructor and copy assignment operator the move constructor and move assignment operator will not be automatically generated. You do not need to explicitly declare them deleted
.
From §12.8/9 (Emphasis added)
If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if
— X does not have a user-declared copy constructor,
— X does not have a user-declared copy assignment operator,
— X does not have a user-declared move assignment operator,
— X does not have a user-declared destructor, and
— the move constructor would not be implicitly defined as deleted.
From §12.8/20 (Emphasis added)
If the definition of a class X does not explicitly declare a move assignment operator, one will be implicitly declared as defaulted if and only if
— X does not have a user-declared copy constructor,
— X does not have a user-declared move constructor,
— X does not have a user-declared copy assignment operator,
— X does not have a user-declared destructor, and
— the move assignment operator would not be implicitly defined as deleted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With