我有這段代碼正在編譯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,因此它與呼叫不匹配)。
uj5u.com熱心網友回復:
在這種情況下,它實際上不是一個移動建構式,它是一個具有通用參考的建構式,因此它同時采用左值和右值。如果你只想將它限制為右值,你應該使用顯式型別:
A(A &&other) {
...
}
我想知道為什么編譯器不呼叫默認的復制建構式(當我洗掉移動建構式或將其引數更改為 時會發生什么
const,因此它與呼叫不匹配)。
請注意,這不會發生,因為如果您顯式添加任何移動操作,復制操作將被隱式洗掉,因此在這種情況下您必須顯式添加它:
A(const A &other) = default;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/537132.html
標籤:C 海合会
