混迹于C++之拷贝赋值函数和拷贝构造函数(三)


#include <stdlib.h>
#include <string.h>
class apple
{
public:
    apple()
    {
        pName = NULL;
        pName = new char[100];
        memset(pName, 0x00, 100*sizeof(char));
    }

    apple(const apple& other)
    {
        *this = other;
    }

    apple& operator=(const apple& other)
    {
        if (this == &other)
        {
            return *this;//同一个对象
        }
        if (pName != NULL)
        {
            delete []pName;//释放原来的指针
            pName = NULL;
        }
        int length = strlen(other.pName);
        this->pName = new char[length];
        memcpy(this->pName, other.pName, length);
        return *this;
    }

    ~apple()
    {
        if (NULL != pName)
        {
            delete []pName;
            pName = NULL;//即使赋值为NULL,也不能阻止出现被释放两次
        }
    }

private:
    char* pName; //类里面含有指针

};

void process(apple* b)
{
    apple* a;
    a = b;
    printf("abOK!\n");
    apple *c,d;//只有一个实例,且申明一个对象指针,指针没有调用构造函数和析构函数,而实例类变变量则会调用析构函数

    c = new apple(d);//调用到拷贝构造函数
    delete c;
    printf("cdOK!\n");

    apple *e,*f;
    e = f; //将e的地址覆盖为f的地址,不是实体变量,没事
    printf("efOK!\n");

    //apple *g, *h;
    //*g = *h;//意图引用空指针,段错误

    printf("i,k Now!\n");
    apple i, j;
    i = j; //调用到赋值构造构造函数
}

int main()
{
    apple b;

    process(&b);
    return 0;
}


//以上用valgrind检测无内存泄漏。
//很多技巧性的东西,不用,不深究它内部的机理,就难免乎略其存在,记之。
 
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值