对象的深拷贝和浅拷贝

对象的深拷贝和浅拷贝

对象占用外部资源时浅拷贝会出问题

自定义拷贝构造函数和赋值重载函数

SeqStack s; //默认构造函数
SeqStack s1(10); // 堆上空间(new int[10]) 对象内存空间 *_pstack _top _size
SeqStack s2 = s1; //默认拷贝构造函数 浅拷贝导致s2的_pstack也指向s1的int[10]
SeqStack s3(s1);  //同上

//自定义拷贝构造函数
SeqStack(const SeqStack &src){
		_pstack = new int[src.size];
		for(int i=0; i<=src._top; i++){
				_pstack[i] = src._pstack[i];
		}
		_top = src._top;
		_size = src._size;
}

//s2.operator=(s1)
//SeqStack& operator=(const SeqStack &src):需要先释放左边对象的外部资源:需要注意 s1 = s1自赋值
s2 = s1; //赋值操作:默认赋值函数 直接的内存拷贝 也会出问题 
// 需要自定义赋值函数(即重载=运算符)

String对象的拷贝

class String
{
public:
		String(const char *str = nullptr) //构造函数
		{
				if(str != nullptr)
				{
						m_data = new char[strlen(str) + 1];
						strcpy(this->m_data, str);
				}
				else
				{
						m_data = new char[1];
						*m_data = '\0';
				}
		}
		String(const String &other) //赋值构造函数
		{
				m_data = new char[strlen(other.m_data)+1];
				strcpy(m_data, other.m_data);
		} 
		~String(void)
		{
				delete[]m_data;
				m_data = nullptr;
		}
		String& operator=(const String &src) //赋值函数重载
		{
				if(this == &src) return *this; //防止自赋值

				delete[]m_data;
				m_data = new char[strlen(src.m_data)+1];
				strcpy(m_data, src.m_data);
				return *this;
		}
private:
		char *m_data; // save str 外部内存
}
// 构造函数
String str1;
String str2("hello");
String str3 = "hello";
// 拷贝构造
String str4 = str3;
String str5(str4);
// 赋值重载函数
str5 = str1;
posted @ 2023-09-10 15:23  我非神灵  阅读(10)  评论(0)    收藏  举报