天天看點

【c++】淺拷貝與深拷貝

// 淺拷貝與深拷貝

// 像這樣的淺拷貝會導緻程式崩潰,因為同一個空間被釋放了兩次
#include <iostream>
#include <string.h>
using namespace std;

class S_Copy;
ostream& operator<<(ostream& out, const S_Copy &s);

class S_Copy
{
	friend ostream& operator<<(ostream& out, const S_Copy &s);
	public:
		S_Copy(const char *str = "")
		{
			p = new char[strlen(str) + 1];
			strcpy(p, str);
		}
		~S_Copy()
		{
			delete[]p;
		}
	private:
		char *p;
};

ostream& operator<<(ostream& out, const S_Copy &s)
{
	out << s.p;
	return out;
}

int main()
{
	S_Copy s1("hello");
	S_Copy s2(s1);
	cout << s2 << endl;
	return 0;
}           

// 如圖,兩個對象裡的指針指向了同一個位址

【c++】淺拷貝與深拷貝
// 深拷貝
#include <iostream>
#include <string.h>
using namespace std;

class S_Copy;
ostream& operator<<(ostream& out, const S_Copy &s);

class S_Copy
{
	friend ostream& operator<<(ostream& out, const S_Copy &s);
public:
	S_Copy(const char *str = "")
	{
		p = new char[strlen(str) + 1];
		strcpy(p, str);
	}
	// 重寫拷貝構造函數,也開辟出一塊空間
	S_Copy(const S_Copy &s)
	{
		p = new char[strlen(s.p) + 1];
		strcpy(p, s.p);
	}
	~S_Copy()
	{
		delete[]p;
	}
private:
	char *p;
};

ostream& operator<<(ostream& out, const S_Copy &s)
{
	out << s.p;
	return out;
}

int main()
{
	S_Copy s1("hello");
	S_Copy s2(s1);
	cout << s2 << endl;
	return 0;
}           
【c++】淺拷貝與深拷貝

繼續閱讀