我有一个用g++.exe -std=c++20编译的代码片段
#include <iostream>
using namespace std;
class A {
public:
A() = delete;
A(int value) : value(value) {}
// A(auto &other) {
// cout << "Copy constructor called..." << endl;
// value = other.value;
// }
void operator=(const auto &other) = delete;
A(auto &&other) {
cout << "Move constructor called..." << endl;
value = other.value;
}
~A() { cout << "Destructor called..." << endl; }
friend ostream &operator<<(ostream &os, const A &a);
private:
int value;
};
ostream &operator<<(ostream &os, const A &a) {
os << a.value;
return os;
}
int main() {
A p1(2);
cout << "p1: " << p1 << endl;
A p2(p1);
cout << "p2: " << p2 << " p1: " << p1 << endl;
return 0;
}我遇到的问题是,当对复制构造函数进行注释时,输出是
Move constructor called...
p2: 2 p1: 2
Destructor called...
Destructor called...如果取消对复制构造函数的注释,输出将变为
p1: 2
Copy constructor called...
p2: 2 p1: 2
Destructor called...
Destructor called...我想知道为什么编译器不只是调用默认的复制构造函数(当我删除移动构造函数或将其参数更改为const时会发生什么情况,因此它与调用不匹配)。
发布于 2022-11-20 23:06:30
在本例中,它实际上不是一个move构造函数,它是一个带有通用参考的构造函数,因此它同时使用lvalue和rvalue。如果只希望将其限制为rvalue,则应使用显式类型:
A(A &&other) {
...
}我想知道为什么编译器不只是调用默认的复制构造函数(当我删除移动构造函数或将其参数更改为
const时会发生什么情况,因此它与调用不匹配)。
请注意,这不会发生,因为如果显式添加任何移动操作,则复制操作将被隐式删除,因此在本例中必须显式添加它:
A(const A &other) = default;https://stackoverflow.com/questions/74512695
复制相似问题