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

zhaoyaqian552發表於2015-05-15
// 淺拷貝與深拷貝

// 像這樣的淺拷貝會導致程式崩潰,因為同一個空間被釋放了兩次
#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;
}

// 如圖,兩個物件裡的指標指向了同一個地址






// 深拷貝
#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;
}


相關文章