C++类_移动构造函数
std::move
的主要用途是在对象所有权转移时,触发移动构造函数或移动赋值运算符,避免不必要的深拷贝,提升性能。
移动构造函数 和 移动赋值运算符, std::move转换为右值,匹配到移动构造函数和移动赋值运算符。
#include <iostream>
#include <utility>class MyClass {
public:// 构造函数MyClass(size_t size) : size(size), data(new int[size]) {std::cout << "Constructor called" << std::endl;for (size_t i = 0; i < size; ++i) {data[i] = i;}std::cout << data << std::endl;}// 析构函数~MyClass() {delete[] data;}// 拷贝构造函数MyClass(const MyClass& other) : size(other.size), data(new int[other.size]) {std::cout << "Copy constructor called" << std::endl;for (size_t i = 0; i < size; ++i) {data[i] = other.data[i];}}// 拷贝赋值运算符MyClass& operator=(const MyClass& other) {std::cout << "Copy assignment operator called" << std::endl;if (this != &other) {delete[] data;size = other.size;data = new int[size];for (size_t i = 0; i < size; ++i) {data[i] = other.data[i];}}return *this;}// 移动构造函数MyClass(MyClass&& other) noexcept : size(other.size), data(other.data) {std::cout << "Move constructor called" << std::endl;other.size = 0;other.data = nullptr;}// 移动赋值运算符MyClass& operator=(MyClass&& other) noexcept {std::cout << "Move assignment operator called" << std::endl;if (this != &other) {delete[] data;size = other.size;data = other.data;other.size = 0;other.data = nullptr;}return *this;}void printData() const {for (size_t i = 0; i < size; ++i) {std::cout << data[i] << " ";}std::cout << data << std::endl;}private:size_t size;int* data;
};int main() {MyClass obj1(5);// 使用 std::move 调用移动赋值运算符MyClass obj2 = std::move(obj1);obj2.printData();MyClass obj3(std::move(obj2));obj3.printData();return 0;
}
// 移动构造函数 MyClass(MyClass&& other)
// 移动赋值运算符 MyClass& operator=(MyClass&& other)
这个两个函数的参数不带const,拷贝构造和拷贝赋值是带const,不能修改成员变量的值。
运行结果: