Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a private move constructor to prevent move?

Tags:

c++

c++11

A common pattern in C++ is to make the copy constructor private:

class A
{
    public:
        // ...
    private:
        A(const A&);
};

But will the following code then compile (in C++11/14):

A f();

auto a = f();

The standard contains information about automatically generating move constructors. I neither have access to the standard nor a compiler which actually generates move constructors. My question is: do I have to write

class A
{
    public:
        // ...
    private:
        A(const A&);
        A(const A&&);
};

to prevent moving as well (and operators= analogously)?

like image 710
Petter Avatar asked Jul 05 '13 16:07

Petter


1 Answers

But will the following code then compile (in C++11/14):

No, it will not. The presence of a user-declared copy constructor should inhibit the implicit generation of a move constructor. Per paragraph 12.8/9 of the C++11 Standard:

If the definition of a class X does not explicitly declare a move constructor, one will be implicitly declared as defaulted if and only if

X does not have a user-declared copy constructor,

— X does not have a user-declared copy assignment operator,

— X does not have a user-declared move assignment operator,

— X does not have a user-declared destructor, and

— the move constructor would not be implicitly defined as deleted.

like image 158
Andy Prowl Avatar answered Oct 07 '22 01:10

Andy Prowl