Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ 移动构造函数

作者:潮起潮落   发布日期:2026-07-26   浏览:33

#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++ 友元类

大家都在看

c++闭包

c++向上取整的代码

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++怎么输入字符串

c++字符串切片

c++ functional

嵌入式c++

c++框架代码

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站