Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does compiler not generate move constructor and move assignment?

Tags:

c++

c++11

In Effective Modern C++, it said

Move operations are generated only for classes lacking explicitly declared move operations, copy operations, and a destructor.

But I tested it with Gcc and Clang, no error was thrown out. So is this rule out of date?

Example program:

#include <iostream>
#include <string>
#include <vector>
#include <memory>

class A
{
    int i;
    public:
    ~A() = default;
};

int main()
{
    A a, b;
    a = b;
    A c(a);
    A d(std::move(a));
    b = std::move(d);
}

Edit: copied "move operations" from the book which might lead to confusion. Changed it to move constructor and move assignment.

like image 478
Cong Ma Avatar asked Dec 06 '25 09:12

Cong Ma


1 Answers

std::move is just a cast to a A&&. The very same xvalue it creates will happily bind to a const A&, which is what the the implicitly defaulted copy c'tor and copy assignment operator accept. So that's what you are calling.

The fact you "appear" to std:move doesn't mean any of those move operations is defined.

If you add a A(A&) = default; to your class, things will start being underlined in red. Because now the copy c'tor accepts a non-const lvalue reference, that will not bind to a A&&.

like image 139
StoryTeller - Unslander Monica Avatar answered Dec 08 '25 21:12

StoryTeller - Unslander Monica