【c++】浅拷贝与深拷贝
时间:2015-05-15 17:41:50
收藏:0
阅读:99
// 浅拷贝与深拷贝
// 像这样的浅拷贝会导致程序崩溃,因为同一个空间被释放了两次
#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;
}
评论(0)