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++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析
- C与C++之间相互调用实例方法讲解