0

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?

8
  • Just separate them, like the first two code block in that section Commented Dec 5, 2016 at 6:46
  • are you referring to copy-and-swap idiom for the assignment operators? Commented Dec 5, 2016 at 6:49
  • vu1p3nox, Yes I am. Commented Dec 5, 2016 at 6:55
  • 1
    Well, what operations do you want your class to support? It is up to you. Commented Dec 5, 2016 at 6:58
  • Also, the "unification" shown has trade-offs. Personally I don't think it is such a good idea. Commented Dec 5, 2016 at 6:59

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Understood completely.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.