C++赋值函数一些考虑

本文探讨了CMyString类中赋值运算符重载的两种实现方式:一种是直接方式,可能引发内存泄漏风险;另一种是更安全的方法,通过局部变量确保即使发生错误也能正确释放资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// Primary programmer use this way
CMyString & CMyString::operator=(const CMyString & str) 
{
	if(this == &str)
		return *this;
	delete [] m_pData;
	m_pData = NULL;
	/*
	* Here may be failed. If this step failed, and next step will
	* failed too. And the pointer m_pData will not point to the
	* original space it will point to NULL. It's so easily lead to crashes.
	*/
	m_pData = new char[strlen(str.m_pData) + 1];
	strcpy(m_pData, str.m_pData);
	return *this;	
}

// The better way
CMyString & CMyString::operator=(const CMyString & str)
{
	if(this != &str)
	{
		/*
		* strTemp is local variable just in scope of "if", so when 
		* program run out of the scope of "if", strTemp will call
		* destructor free the area that strTemp.m_pData point at.
		*/
		CMyString strTemp(str); 
		char *strTemp = strTemp.m_pData;
		/*
		 * so the memory where m_pData point at will been free
		 * by strTemp.m_pData with program run out of the scope
		 * of "if"
		 */
		strTemp.m_pData = m_pData; 
		m_pData = pTemp;
	}
	return *this;
}

### C++ 中拷贝赋值函数的使用方法及其实现 #### 定义与作用 拷贝赋值函数(Copy Assignment Operator),也称为赋值操作符重载函数 `operator=`,用于处理已有对象之间的赋值操作。当一个对象被赋予另一个同类型对象的内容时,会调用此成员函数来完成属性的数据复制过程[^2]。 对于自定义类而言,默认情况下编译器提供了一个简单的位对位拷贝版本;然而,在某些场景下——比如管理动态内存或其他资源时,则需自行定义以确保正确的行为并防止潜在错误的发生[^4]。 #### 实现方式 通常来说,拷贝赋值函数会在类内部声明如下形式: ```cpp class MyClass { public: // ...其他成员... MyClass& operator=(const MyClass& rhs); }; ``` 这里返回类型为当前类的一个引用 (`MyClass&`) 是为了支持链式赋值表达式的书写习惯,即允许像 a=b=c 这样的连续赋值语句正常工作[^3]。 实际编写时需要注意自我赋值的情况以及如何释放旧有的资源再分配新的副本等问题。下面给出一段较为完整的例子说明其具体做法: ```cpp #include <iostream> using namespace std; class String { private: char* data; public: explicit String(const char* str = "") :data(new char[strlen(str)+1]) { strcpy(data, str); } ~String() { delete[] data; } /// @brief 拷贝赋值运算符 String& operator=(const String& rhs) { if(this != &rhs){ // 防止自我赋值带来的问题 // 清理现有资源 delete [] this->data; // 复制新内容 size_t length = strlen(rhs.data); this->data = new char[length + 1]; strncpy(this->data,rhs.data,length+1); } return *this; } void display() const{ cout << "Data: " << data << endl; } }; int main(){ String s1("hello"); String s2; s2.display(); s2 = s1; s2.display(); return 0; } ``` 在这个案例里展示了怎样安全有效地执行字符串类型的深拷贝逻辑,同时也考虑到了特殊情况下的边界条件处理[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值