string类的深浅拷贝问题

时间:2022-06-06 21:22:18

  字符串是我们在编写程序的时候经常用的到的。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;
};