C++基础-构造函数(指针+基础变量)

C++构造函数(指针与基础变量)
#include <iostream>
#include <cstring>

class MyData {
public:
    int id;          // 基础变量
    char* name;      // 指针变量,指向动态分配的内存

    // 默认构造函数
    MyData(int id_, const char* name_)
        : id(id_), name(new char[strlen(name_) + 1])
    {
        std::strcpy(name, name_);
        std::cout << "Constructor: " << name << std::endl;
    }

    // 拷贝构造函数
    MyData(const MyData& other)
        : id(other.id), name(new char[strlen(other.name) + 1])
    {
        std::strcpy(name, other.name);
        std::cout << "Copy Constructor: " << name << std::endl;
    }

    // 拷贝赋值运算符
    MyData& operator=(const MyData& other)
    {
        if (this != &other) {
            delete[] name;
            id = other.id;
            name = new char[strlen(other.name) + 1];
            std::strcpy(name, other.name);
            std::cout << "Copy Assignment: " << name << std::endl;
        }
        return *this;
    }

    // 移动构造函数
    MyData(MyData&& other) noexcept
        : id(other.id), name(other.name)
    {
        other.name = nullptr;
        std::cout << "Move Constructor" << std::endl;
    }

    // 移动赋值运算符
    MyData& operator=(MyData&& other) noexcept
    {
        if (this != &other) {
            delete[] name;
            id = other.id;
            name = other.name;
            other.name = nullptr;
            std::cout << "Move Assignment" << std::endl;
        }
        return *this;
    }

    // 析构函数
    ~MyData()
    {
        std::cout << "Destructor: " << (name ? name : "null") << std::endl;
        delete[] name;
    }
};
int main() {
    MyData a(1, "alpha");               // 普通构造
    MyData b = a;                       // 拷贝构造
    MyData c(2, "charlie");
    c = a;                              // 拷贝赋值

    MyData d = std::move(a);           // 移动构造
    MyData e(3, "echo");
    e = std::move(b);                  // 移动赋值
}
类型使用时机通常目的
拷贝构造初始化时 A a = b;深拷贝,复制资源
拷贝赋值已存在对象赋值 a = b;释放原资源,再复制
移动构造初始化时 A a = std::move(b);“窃取”资源,提高性能
移动赋值a = std::move(b);释放原资源,窃取右值资源
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值