聊下类的浅拷贝问题

一句话总结:防止浅拷贝释放指针所造成的异常问题。

#include <stdio.h>

class A{
   int i;
};

class B{
   A *p;
public:
   B()
   {
       printf("construct B\n");
       p=new A;
   }
   ~B()
   {
       printf("destruct B\n");
       if (p != NULL) 
       {
           printf("p is not NULL\n");
           delete p;
           p = NULL;
       }
       else
           printf("p is NULL\n");
   }
   /* 默认的拷贝构造函数,属于浅拷贝
   B(const B& ths){
       p = ths.p;
   }*/
};

void fun(B b){
}

int main(){
   B b;
   fun(b);
}

结果:

construct B

destruct B

p is not NULL

destruct B

p is not NULL

test2(59615,0x7fff768c4000) malloc: *** error for object 0x7fd1f2401470: pointer being freed was not allocated

*** set a breakpoint in malloc_error_break to debug

Abort trap: 6


从结果看出,指针p指向的内存要被释放两次。

修改拷贝赋值函数,进行深拷贝。

#include <stdio.h>

class A{
   int i;
};

class B{
   A *p;
public:
   B()
   {
        printf("construct B\n");
        p=new A;
   }
   ~B()
   {
        printf("destruct B\n");
        if (p != NULL) 
        {
             printf("p is not NULL,delete p\n");
             delete p;
             p = NULL;
        }
        else
             printf("p is NULL\n");
   }
   /* 默认的拷贝构造函数,属于浅拷贝
   B(const B& ths){
       p = ths.p;
   }*/
   B(const B& other){
        printf("copy an object\n");
    	p = new A;       //构建新的指针
       	*p = *(other.p); //将指向的内容复制,依然指向不同的位置
   }
};

void fun(B b){
}

int main(){
   B b;
   fun(b);
}

此时正常

construct B

copy an object

destruct B

p is not NULL,delete p

destruct B

p is not NULL,delete p




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值