1. 移动语义与资源管理类设计基础
在C++中,资源管理类(如智能指针、文件句柄、网络连接等)负责管理动态分配的资源。传统C++通过拷贝构造函数和拷贝赋值运算符实现对象复制,但这在资源管理场景下存在明显缺陷:
cpp复制class FileHandle {
public:
FileHandle(const char* filename) {
handle = fopen(filename, "r"); // 获取资源
}
~FileHandle() {
if (handle) fclose(handle); // 释放资源
}
private:
FILE* handle;
};
当这类对象被拷贝时,简单的指针复制会导致多个对象管理同一资源,引发双重释放问题。C++11引入移动语义后,我们可以通过转移资源所有权而非复制资源来解决这个问题。
1.1 右值引用与移动语义实现
移动语义的核心是右值引用(T&&),它专门绑定到临时对象(右值)。资源管理类应实现移动构造函数和移动赋值运算符:
cpp复制class FileHandle {
public:
// 移动构造函数
FileHandle(FileHandle&& other) noexcept
: handle(other.handle) {
other.handle = nullptr; // 源对象放弃资源所有权
}
// 移动赋值运算符
FileHandle& operator=(FileHandle&& other) noexcept {
if (this != &other) {
if (handle) fclose(handle);
handle = other.handle;
other.handle = nullptr;
}
return *this;
}
// 禁用拷贝操作
FileHandle(const FileHandle&) = delete;
FileHandle& operator=(const FileHandle&) = delete;
private:
FILE* handle;
};
关键设计要点:
- 移动操作必须标记为
noexcept,否则标准库容器在扩容时不会使用移动 - 移动后必须将源对象置于有效但可析构状态(通常置空指针)
- 资源管理类通常应禁用拷贝操作(三/五法则)
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 完美转发在工厂模式中的应用
完美
