Disabling the move constructor

I would like to disable the move constructor in the class. Instead of moving, I would like to rely on the copy constructor. When I try to write this code:

class Boo { public: Boo(){} Boo(const Boo& boo) {}; Boo(Boo&& boo) = delete; }; Boo TakeBoo() { Boo b; return b; } 

during compilation i got an error:

error C2280: 'Boo :: Boo (Boo &)': attempt to reference a remote function

How can I disable the move constructor and force copy copies?

+7
c ++ c ++ 11 move
source share
2 answers

Do not create a move constructor:

 class Boo { public: Boo(){} Boo(const Boo& boo) {}; }; 

A move constructor is not created automatically, provided that a custom copy constructor is present, so the copy constructor is called.

+17
source share

Marking the function as =delete makes the function available for overload resolution, but if selected, compilation fails; this functionality is not limited to designers and other special functions (see here) . Previously (around C ++ 03), which made it private, achieved a similar result.

Therefore, the code, as in the example, actually means that you prohibit the construction of a class object from a temporary or expiring value (rvalues) - a constructor for moving.

To fix this, completely remove the move constructor. In the case of a class where the copy constructor is present (user-defined), the movement is not implicitly generated in any case (movement of the constructor and movement destination operator).

 class Boo { public: Boo(){} Boo(const Boo& boo) {}; //Boo(Boo&& boo) = delete; }; 
+4
source share

All Articles