Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling move constructor

Tags:

c++

c++11

move

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?

like image 660
user5929018 Avatar asked Feb 15 '16 09:02

user5929018


People also ask

How do I turn off 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).

Is move constructor automatically generated?

No move constructor is automatically generated.

What is a move constructor?

A move constructor allows the resources owned by an rvalue object to be moved into an lvalue without creating its copy. An rvalue is an expression that does not have any memory address, and an lvalue is an expression with a memory address.

What does the default move constructor do?

For non-union class types (class and struct), the move constructor performs full member-wise move of the object's bases and non-static members, in their initialization order, using direct initialization with an xvalue argument.


1 Answers

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.

like image 200
Marian Spanik Avatar answered Nov 07 '22 07:11

Marian Spanik