[英]C++ move semantics: why copy assignment operator=(&) is called instead of move assignment operator=(&&)?
我有以下代碼:
#include <cstdio>
#include <iostream>
using std::cout;
struct SomeType {
SomeType() {}
SomeType(const SomeType &&other) {
cout << "SomeType(SomeType&&)\n";
*this = std::move(other);
}
void operator=(const SomeType &) {
cout << "operator=(const SomeType&)\n";
}
void operator=(SomeType &&) {
cout << "operator=(SomeType&&)\n";
}
};
int main() {
SomeType a;
SomeType b(std::move(a));
b = std::move(a);
return 0;
}
我希望移動構造函數調用移動賦值運算符。 這是該程序的輸出:
SomeType(SomeType&&)
operator=(const SomeType&)
operator=(SomeType&&)
如您所見,移動賦值運算符已成功調用,但在分配給*this
inside move構造函數時則不會。 為什么會這樣,我能以某種方式修復它嗎?
你的移動構造函數采用const SomeType&&
而不是SomeType&&
。 你不能調用一個帶有SomeType&&
(你的移動構造函數)的函數,其值為const SomeType&&
。
嘗試制作一個帶有SomeType&&
的移動構造函數。
std::move
轉換為r值引用。 因此它將other
內容轉換為const SomeType &&
。 這當然不能綁定到SomeType &&
,所以它回退到const SomeType &
。
從移動構造函數的參數中刪除const
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.