Reputation: 2669
#include <utility>
class A {
int* ptr;
public:
A() {
ptr = new int[10];
}
A(A&& rhs) {
this->ptr = rhs.ptr;
rhs.ptr = nullptr;
}
~A() {
if (ptr) delete[] ptr;
}
};
int main() {
A a1;
A a2;
a2 = std::move(a1);
}
GCC 11 complains that the copy assignment operator is deleted:
<source>: In function 'int main()':
<source>:23:22: error: use of deleted function 'constexpr A& A::operator=(const A&)'
23 | a2 = std::move(a1);
| ^
<source>:3:7: note: 'constexpr A& A::operator=(const A&)' is implicitly declared as deleted because 'A' declares a move constructor or move assignment operator
3 | class A {
| ^
Compiler returned: 1
Then, after I defined the move assignment operator (not copy assignment operator), it compiled fine. Then, it means compiler is indeed looking for move assignment operator, which I expected. I don't understand why when the move assignment operator is implicitly deleted, the compiler would look for the copy assignment operator. Any idea? Or it is just a bad error message from compiler?
Upvotes: 2
Views: 245
Reputation: 23547
Your explanation is not exactly correct. The compiler wasn't looking particularly for operator=(A&&)
. It was simply looking for any operator=
that could be called for that assignment.
Now, the move assignment operator operator=(A&&)
doesn't exist at all. However, the copy assignment operator operator=(const A&)
does exist, but it is defined as deleted.
Therefore, the copy assignment operator is the only operator that can be used for that assignment (since constant lvalue references can bind rvalues). The compiler tries to use it but finds out that it is deleted, which triggers that compilation error.
Upvotes: 5