#include <iostream>
#include <utility> // for std::move
class MyClass {
public:
// 默认构造函数
MyClass() : data(new int[10]) {
std::cout << "Default constructor called\n";
}
// 拷贝构造函数
MyClass(const MyClass& other) : data(new int[10]) {
std::cout << "Copy constructor called\n";
for (int i = 0; i < 10; ++i) {
data[i] = other.data[i];
}
}
// 移动构造函数
MyClass(MyClass&& other) noexcept : data(other.data) {
std::cout << "Move constructor called\n";
other.data = nullptr; // 确保源对象不再拥有资源
}
// 析构函数
~MyClass() {
delete[] data;
std::cout << "Destructor called\n";
}
private:
int* data;
};
int main() {
MyClass obj1;
MyClass obj2 = std::move(obj1); // 调用移动构造函数
return 0;
}
data,分配内存。data 数组的内容。std::move)初始化时调用,直接转移 data 指针的所有权,并将源对象的指针置为 nullptr,以确保源对象不再拥有资源。通过这个例子,可以看到移动构造函数在资源管理中的高效性,避免了不必要的深拷贝操作。
上一篇:c++判断回文数
下一篇:c++ 友元类
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站