模拟实现string类

来源:互联网 发布:手机统计软件 编辑:程序博客网 时间:2024/06/12 18:56

深浅拷贝:

浅拷贝:也称位拷贝,编译器只是直接将指针的值拷贝过来,结果多个对象共用同一块内存,当一个对象将这块内存释放掉之后,另一些对象不知道该块空间已经还给了系统,以为还有效,所以在对这段内存进行释放操作的时候一个内存空间被释放多次,发生了访问违规,程序崩溃。

深拷贝:为了解决浅拷贝的问题,深拷贝则不是直接将指针的值拷贝,它是为指针p2开辟与p1相同大小的内存空间,然后将p1所指的内存str[]内容拷贝到p2自己空间中,这时由于p1、p2指向的是各自不同的内存空间,delete时只释放自己的内存,不会出现访问违规。

普通版本的string类:

class mystring{public:    mystring(const char* str = "")        :_str(new char[strlen(str)+1])    {        strcpy(_str, str);    }    mystring(const mystring& s)        :_str(new char[strlen(s._str)+1])    {        strcpy(_str, s._str);    }    mystring& operator=(const mystring& s)    {        if (this != &s)        {            delete[] _str;            _str = new char[strlen(s._str) + 1];            strcpy(_str, s._str);        }        return*this;    }    ~mystring()    {        if (_str != NULL)        {            delete[] _str;            _str = NULL;        }    }private:    char* _str;};

模拟实现string类的简洁版本

class mystring{public:    mystring(const char* str = "")        :_str(new char[strlen(str)+1])    {        strcpy(_str, str);    }    mystring(const mystring& s)    {        mystring tmp(s._str);        swap(_str, tmp._str);    }    mystring& operator=(mystring s)    {        swap(_str, s._str);        return *this;    }    ~mystring()    {        if (_str != NULL)        {            delete[] _str;            _str = NULL;        }    }private:    char* _str;};
原创粉丝点击