C++ 11 默认的六个构造

11 篇文章 0 订阅

默认的六个构造

#include <iostream>
using namespace std;
//系统默认提供的构造
#include <iostream>
using namespace std;

class A {
public:
    // 构造函数,接受一个整数参数,默认为0
    A(int i = 0) {
        _i = new int; // 动态分配内存
        *_i = i; // 将传入的值赋给动态分配的内存
        cout << "A()" << endl;
    }

    // 析构函数
    ~A() {
        if (_i != nullptr) { // 检查指针是否为空
            delete _i; // 释放动态分配的内存
        }
        cout << "~A()" << endl;
    }

    // 拷贝构造函数
    A(const A &another) {
        _i = new int; // 动态分配新的内存
        *_i = *another._i; // 将另一个对象的值拷贝到新分配的内存中
        cout << "A(const A &another)拷贝构造函数" << endl;
    }

    // 移动构造函数
    A(A &&another) {
        _i = another._i; // 将另一个对象的指针直接赋值给当前对象
        another._i = nullptr; // 将另一个对象的指针置为空,防止重复释放
        cout << "A(A &&another)移动构造函数" << endl;
    }

    // 赋值拷贝运算符
    A &operator=(const A &another) {
        if (this != &another) { // 检查是否是自我赋值
            delete _i; // 释放当前对象的内存
            _i = new int; // 动态分配新的内存
            *_i = *another._i; // 将另一个对象的值拷贝到新分配的内存中
        }
        cout << "A &operator=(const A &another)赋值拷贝运算符" << endl;
        return *this; // 返回当前对象的引用
    }

    // 移动赋值运算符
    A &operator=(A &&another) {
        if (this != &another) { // 检查是否是自我赋值
            delete _i; // 释放当前对象的内存
            _i = another._i; // 将另一个对象的指针直接赋值给当前对象
            another._i = nullptr; // 将另一个对象的指针置为空,防止重复释放
        }
        cout << " A &operator=(A &&another) 移动赋值运算符" << endl;
        return *this; // 返回当前对象的引用
    }
protected:
    int *_i; // 指向动态分配内存的指针
};


int main() {
    A a;
    A b(a);//A(const A &another)拷贝构造函数

    A c(std::move(a));//A(A &&another)移动构造函数
    //此时a已经null

    A d = c; //A(const A &another)拷贝构造函数

    A e =std::move(d);//A(A &&another)移动构造函数

    A f;
    f=std::move(e); //A &operator=(A &&another) 移动赋值运算符
    //此时e已经null
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MarkTop1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值