您的位置:首页 > 编程语言 > C语言/C++

C++中的三大缺省函数 之 《深拷贝与浅拷贝》

2016-07-06 00:12 363 查看
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

class  Test
{
public:
void show(void)
{
cout <<data<< endl;
}
public:

Test(char *str = "")
{
if(str == '\0'){
data = (char *)malloc(sizeof(char));
data[0] = '\0';
}else{
data = (char *)malloc(sizeof(char)*strlen(str) + 1);
strcpy(data,str);
}

cout <<this<<"构造函数"<<endl;
}

~Test()
{    cout <<data;
free(data);
cout << "data free"<<endl;
data = NULL;
cout << this<<"析构函数"<<endl;
}


段错误原因:同一空间释放了多次,由于赋值函数系统默认,只是简单的把指针的值赋予新建对象,即就是

                    对象1与对象2指向同一空间,就是浅拷贝,在对象析构时,发生而同一空间多次释放

改正:

             自己写对应的拷贝函数,赋值函数,实现深拷贝

小结:

            有时不能默认使用编译器的赋值,拷贝构造函数

改进后的代码:

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

class Test
{
public:
void show(void)
{
cout <<data<< endl;
}
public:

Test(char *str = "")
{
if(str == '\0'){
data = (char *)malloc(sizeof(char));
data[0] = '\0';
}else{
data = (char *)malloc(sizeof(char)*strlen(str) + 1);
strcpy(data,str);
}

cout <<this<<"构造函数"<<endl;
}
Test &operator = (Test &sd)
{
if(this != &sd)
{
data = (char *)malloc(sizeof(char)*strlen(sd.data)+1);
strcpy(data,sd.data);
}
cout <<this <<"赋值函数"<<endl;
return *this;
}

~Test()
{ cout <<data;
free(data);
cout << "data free"<<endl;
data = NULL;
cout << this<<"析构函数"<<endl;
}

private:
char *data;

};
int main()
{

Test t;
Test t1("liusenlin");
t = t1;
return 0;

}

0018FF38构造函数

0018FF34构造函数

0018FF38赋值函数

liusenlindata free

0018FF34析构函数

liusenlindata free

0018FF38析构函数

Press any key to continue
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++