温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

简单的String类实现及写时拷贝

发布时间:2020-05-29 03:59:49 来源:网络 阅读:242 作者:yayaru9240 栏目:编程语言
#include<iostream>
using namespace std;

class String
{
public:
	/*String(const char* str=" ")
		:_str(new char[strlen(str)+1])
	{
		strcpy(_str, str);
	}
*/
	String(const char* str = " ")
	{
		if (str == NULL)
		{
			_str = new char;
			_str[0] = '\0';
		}
		else
		{
			_str = new char[strlen(str) + 1];
			strcpy(_str, str);
		}	
	}
	/*String(const String& other)
		:_str(NULL)
	{
		_str = new char[strlen(other._str) + 1];
		strcpy(_str, other._str);
	}*/

	String(const String& other)
		:_str(NULL)
	{
		String tmp(other._str);//创建一个临时对象
		swap(_str, tmp._str);
	}

	String& operator=(String& other)
	{
		if (this != &other)
		{
			delete[] _str;
			_str = new char[strlen(other._str) + 1];
			strcpy(_str, other._str);
		}
		return *this;//返回值支持链式表达式
	}

	char *GetStr()
	{
		return _str;
	}

	char& operator[](size_t index)//若不用引用,再它返回时会返回一个匿名对象为一个常量不可改变
	{
		return _str[index];
	}
	/*String& operator=(String other)
	{
		swap(_str, other._str);//现代写法即传过来一个临时对象
		return *this;
	}*/

	~String()
	{
		if (_str)
			delete[] _str;
	}
protected:
	char *_str;
};

void Test()
{
	char* ptr = "abcd";
	String s1(ptr);
	String s2(s1);
	String s3("def");
	s3 = s2;
	//s1[0] = 'x';
	cout<<s3.GetStr() << endl;
}

若只定义一个全局的整型变量,它只适用于指向同一个内存块。

用引用计数解决浅拷贝后多次析构崩溃问题(写时拷贝),每块空间都有各自的指针指向。

#include<iostream>
using namespace std;
class String
{
public:
String(const char* str = " ")
:_str(new char[strlen(str) + 5])
{
*((int*)_str) = 1; //多开4字节空间保存有几个指针指向该块空间
_str += 4;
strcpy(_str, str);
}
/*String(const char* str = " ")
{
if (str == NULL)
{
_str = new char;
_str[0] = '\0';
}
else
{
_str = new char[strlen(str) + 1];
strcpy(_str, str);
}
}*/
String(const String& other)
:_str(other._str)
{
++*(((int*)_str)-1);
}
//String(const String& other)
//:_str(NULL)
//{
//String tmp(other._str);//创建一个临时对象
//swap(_str, tmp._str);
//}
String& operator=(String& other)
{
if (this != &other)
{
if (--*(((int*)_str) - 1) == 0)
{
//若只有一个指针指向该空间则释放掉它,让其重新指向另一块空间
_str -= 4;//释放空间时一定从头释放
delete[] _str;
}
}
_str = other._str;
++*(((int*)(other._str))-1);
return *this;//返回值支持链式表达式
}
char *GetStr()
{
return _str;
}
char& operator[](size_t index)//若不用引用,再它返回时会返回一个匿名对象为一个常量不可改变
{
return _str[index];
}
/*String& operator=(String other)
{
swap(_str, other._str);//现代写法即传过来一个临时对象
return *this;
}*/
~String()
{
if (_str)
{
if (--*(((int*)_str) - 1) == 0)
{
_str -= 4;  //释放空间时一定从头释放
delete[] _str;
}
}
}
protected:
char *_str;
};
void Test()
{
char* ptr = "abcd";
String s1(ptr);
String s2(s1);
String s3("def");
s3 = s2;
//s1[0] = 'x';
cout << s3.GetStr() << endl;
}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI