Reputation: 83
I've read here: What are move semantics?, under secondary title: Special member functions, the reasons why we should unify both copy assignment operator & move assignment operator into a single move\copy assignment operator,
but what if we wish to forbid copying or moving? should in this case I indicate "deleted" on the forbidden constructor and implement the other? (i.e. separating between the two).
If so, what is the proper way to do it?
Upvotes: 0
Views: 134
Reputation: 30494
If you want to create a class that is movable but not copyable, you should implement the move constructor and mark the copy constructor as deleted.
The copy-and-swap pattern still works (more of a move-and-swap, really). Since the parameter can only be move constructed, only move assignment will be available.
class MyClass
{
MyClass(MyClass&& other) {
// Do your move here
}
MyClass(const MyClass& other) = delete;
MyClass& operator=(MyClass other) {
// You can still use copy-and-swap (move-and-swap, really)
// Since MyClass is non-copyable, only move assignment will be available
}
};
Or you could just create a move assignment operator (MyClass& operator=(MyClass&& other)
) instead. The default copy assignment operator will be implicitly deleted if you declare a move constructor.
Upvotes: 2