右移是否可以理解为将一个变量的资源转化为目标变量的资源?
右移的核心操作:
举个简单的例子:
#include <iostream>
#include <string>
class MyClass {
public:
std::string* data;
// 普通构造函数
MyClass(const std::string& str) : data(new std::string(str)) {
std::cout << "Constructed: " << *data << std::endl;
}
// 移动构造函数
MyClass(MyClass&& other) noexcept {
data = other.data; // 转移资源的所有权
other.data = nullptr; // 将源对象的资源指针置空
std::cout << "Moved!" << std::endl;
}
// 析构函数
~MyClass() {
if (data) {
std::cout << "Destroyed: " << *data << std::endl;
delete data;
}
}
};
int main() {
MyClass a("Hello");
MyClass b = std::move(a); // 右移:将 a 的资源转移到 b
return 0;
}代码解释:
为什么说右移是将变量的资源转化为目标变量的资源?
区别于拷贝语义:
右移的好处:
总结:
Last updated