C++98 中臨時對象(右值)只能綁定到 const 左值引用,導致不必要的深拷貝。C++11 引入右值引用 T&&,允許「盜取」臨時對象資源。
class MemoryBlock {
size_t _len; int* _data;
public:
// 移動構造
MemoryBlock(MemoryBlock&& other) noexcept
: _len(other._len), _data(other._data) {
other._len = 0; other._data = nullptr;
}
// 移動賦值
MemoryBlock& operator=(MemoryBlock&& other) noexcept {
if (this != &other) {
delete[] _data;
_len = other._len; _data = other._data;
other._len = 0; other._data = nullptr;
}
return *this;
}
};
std::move(x) 將左值轉為右值引用,聲明「可被移動」。std::forward 實現完美轉發,保持值類別。文中給出兩個基準測試:
s1+s2+s3+s4 循環 3000 萬次:使用 return std::move(tmp) vs 直接 return tmp,前者快 30-40%。MemoryBlock 移動 vs 拷貝 10 萬次:移動快 ~30%。noexcept,否則標準庫容器擴容時不敢用移動(退回拷貝)。unique_ptr、shared_ptr 內部大量使用移動語義。作者感嘆 C++ 不斷做加法(語法複雜度上升),學習成本高,建議標準委員會考慮做減法。但移動語義確實解決了長期存在的性能痛點。