定义移动构造函数和移动赋值运算符允许在不复制数据的情况下移动函数对象。移动构造函数:通过使用 rvalue 引用捕捉所有权,将数据移动,无需复制。移动赋值运算符:通过使用 std::swap,将数据移动,无需复制,并返回自身引用。实战案例:使用移动构造函数和移动赋值运算符优化函数类的函数对象的移动。

C++ 函数类的移动构造函数和移动赋值运算符
定义
移动构造函数和移动赋值运算符允许我们在不复制数据的情况下移动函数对象。这是通过使用 rvalue 引用来捕捉函数对象的所有权。
立即学习“C++免费学习笔记(深入)”;
移动构造函数
class FunctionClass {
public:
FunctionClass(FunctionClass&& other) noexcept {
// 移动存储的数据,无需复制
std::swap(data_, other.data_);
}
// ...
};移动赋值运算符
class FunctionClass {
public:
FunctionClass& operator=(FunctionClass&& other) noexcept {
// 移动存储的数据,无需复制
std::swap(data_, other.data_);
return *this;
}
// ...
};实战案例
考虑一个存储数据的函数类:
class DataStorage {
public:
DataStorage(std::vector data) : data_(std::move(data)) {}
// ...
private:
std::vector data_;
}; 可以使用移动构造函数和移动赋值运算符优化函数类的数据传输,而不进行昂贵的复制操作:
// 优化后的代码
class DataStorage {
public:
DataStorage(DataStorage&& other) noexcept : data_(std::move(other.data_)) {}
DataStorage& operator=(DataStorage&& other) noexcept {
data_ = std::move(other.data_);
return *this;
}
// ...
private:
std::vector data_;
}; 注意事项
- 移动操作只能在 rvalue 函数对象上执行(即,当函数对象不存在左值时)。
- 移动操作通常比复制操作更快,因为它们不涉及数据复制。
- 移动操作应该是无异常的(noexcept),以确保数据的正确性。










