为什么右值实现移动语义?为什么避免了拷贝?难道左值就要拷贝么?
1. 移动语义与拷贝语义的区别:
MyClass a; MyClass b = a; // 拷贝 a,产生 b 的副本,资源被复制MyClass a; MyClass b = std::move(a); // 移动 a 的资源到 b,a 被清空
2. 为什么右值可以实现移动语义?
MyClass(MyClass&& other) noexcept { this->data = other.data; // 移动资源 other.data = nullptr; // 将 other 清空 }
3. 为什么避免了拷贝?
4. 左值需要拷贝么?
总结:
Last updated