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

来源:互联网 发布:matlab trapz函数算法 编辑:程序博客网 时间:2024/05/28 06:05
#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
原创粉丝点击