C++移动构造和移动赋值概念
移动构造函数(Move Constructor)
- 是一种特殊的构造函数,用来“移动”一个临时对象(右值)的资源(如动态内存、文件句柄等)到新对象中,而不是进行资源的深拷贝。
- 通过接收右值引用参数(Type&&)实现。
- 移动后,源对象通常被置于有效但未定义状态(比如指针置为 nullptr),以避免资源重复释放。
- 目的是提高性能,减少不必要的复制开销。
移动赋值操作符(Move Assignment Operator)
- 是一种赋值操作符,用来将一个右值对象的资源“移动”到已有对象中,类似移动构造,但针对赋值场景。
- 也是通过右值引用参数实现。
- 实现时需要先释放当前对象已有资源,然后接管源对象资源。
English: Move Constructor and Move Assignment Concept
Move Constructor
- A special constructor that “moves” resources (like dynamic memory or file handles) from a temporary (rvalue) object to a new object instead of performing a deep copy.
- Implemented by taking an rvalue reference parameter (Type&&).
- After moving, the source object is left in a valid but unspecified state (e.g., pointers set to nullptr) to avoid double freeing.
- Aimed at improving performance by avoiding unnecessary copies.
Move Assignment Operator
- An assignment operator that “moves” resources from an rvalue object to an existing object, similar to move constructor but for assignment.
- Also implemented using rvalue references.
- Typically releases current resources of the target object before taking ownership of the source’s resources.
简单示例 Example
class MyString {
char* data;
public:
// 移动构造函数
MyString(MyString&& other) noexcept : data(other.data) {
other.data = nullptr; // 移动后置空源指针
}
// 移动赋值操作符
MyString& operator=(MyString&& other) noexcept {
if (this != &other) {
delete[] data; // 释放原资源
data = other.data; // 接管资源
other.data = nullptr;
}
return *this;
}
~MyString() { delete[] data; }
};