字符串是我们在编写程序的时候经常用的到的。C++库已经帮我们实现了一个功能更加强大的字符串类string,我们要去了解它是怎么实现的。
只要是涉及到 string类的地方多少都会涉及到深浅拷贝的问题。在C++中,在用一个对象初始化另一个对象时,只复制了成员,并没有复制资源,使两个对象同时指向了同一资源的复制方式称为浅复制。
深拷贝是将指向内容复制到给当前对象新分配的缓冲区中的一种复制方式。
下面就是自己实现的深拷贝string类:
#include<iostream>
#include<string.h>
using namespace std;
class String
{
public:
String(const char* str="")
:_str(new char[strlen(str)+1])
{
strcpy(_str, str);
}
//深拷贝
String(const String& s)
:_str(new char[strlen(s._str)+1])
{
strcpy(_str, s._str);
}
String& operator=(const String& s)
{
if (this != &s)
{
delete[] _str;
_str = new char[strlen(s._str) + 1];
strcpy(_str, s._str);
}
return *this;
}
////现代写法
//String(const String& s)
// :_str(NULL)
//{
// String tmp(s._str);
// swap(tmp._str,_str);
//}
//String& operator=(const String& s)
//{
// if (this != &s)
// {
// _str = NULL;
// String tmp(s);
// swap(tmp._str, _str);
// }
// return *this;
//}
private:
char* _str;
};
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。