Violet Giraffe
Violet Giraffe

Reputation: 33589

How to delete the move assignment operator and retain compatibility with std containers?

I have a simple RAII wrapper for managing a certain resource. Here's the interface:

struct ResourceWrapper
{
    explicit ResourceWrapper(RESOURCE resource);
    ResourceWrapper(const ResourceWrapper& other);
    ResourceWrapper& operator=(const ResourceWrapper& other);
    ~ResourceWrapper();

    ResourceWrapper(ResourceWrapper&& other) = delete;
    ResourceWrapper& operator=(ResourceWrapper&& other) = delete;
};

The problem here is that I can no longer use this class with std containers and algorithms as soon as I explicitly delete the move assignment operator. And obviously I do need to either delete or properly implement it, as I've just learned the hard way.

Another alternative would be to implement move assignment via the regular assignment operator, but I'm not sure how to do that properly. I suppose I need something like std::remove_reference? I wonder if it will remove one reference too many and incur creation of unnecessary temporary object.

Upvotes: 4

Views: 675

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171303

And obviously I do need to either delete or properly implement it, as I've just learned the hard way.

No you don't.

Your class has a user-defined copy constructor, copy assignment operator and destructor, so the compiler will not define a move assignment operator for you.

So just stop trying to delete it, and the class will be copied instead of moved.

With deleted move operations you cannot copy rvalues of the type, i.e. it becomes extremely difficult to use as a value type (including in containers). With no move operations it will just do a deep copy of rvalues, which is safe and probably what you want.

Deleting the move operations only makes sense if you want the class to be completely un-movable and un-copyable, e.g. something like a mutex type where object identity is critical, not its value. It never makes sense to have a copyable type with deleted moves.

Upvotes: 14

Related Questions