聊下类的浅拷贝问题

来源:互联网 发布:f6 转换为65533 java 编辑:程序博客网 时间:2024/06/05 02:04

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

#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




原创粉丝点击