Reputation: 201
I would like to disable the move constructor in the class. Instead of moving, I would like to base on 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 received error:
error C2280: 'Boo::Boo(Boo &&)': attempting to reference a deleted function
How can I disable the move constructor and force copies instead?
Upvotes: 15
Views: 7222
Reputation: 30605
Marking a function as =delete
makes the function available for overload resolution, but if chosen, the compilation fails; this functionality is not limited to constructors and other special functions (see here). Previously (circa C++03) making the member private achieved a similar result.
Hence, the code as in the sample, effectively means you prohibiting the construction of an object of the class from a temporary or expiring value (rvalues) - the move constructor.
To correct this, remove the move constructor completely. In the case of the class, once a copy constructor is present (user defined), the move is implicitly not generated anyway (move constructor and move assignment operator).
class Boo
{
public:
Boo(){}
Boo(const Boo& boo) {};
//Boo(Boo&& boo) = delete;
};
Upvotes: 10
Reputation: 1109
Do not create any move constructor:
class Boo
{
public:
Boo(){}
Boo(const Boo& boo) {};
};
The move constructor is not automatically generated as long as a user-defined copy constructor is present so the copy constructor is called.
Upvotes: 26