C++中由于浅拷贝造成的程序中断错误的简例(编译通过,运行出现中断)
2018-02-26 00:50
507 查看
问题:C++中由于浅拷贝造成的程序中断错误的简例(编译通过,运行出现中断)本程序通过VC++ 6.0编译与测试,程序设计为在指针中存入(0—4),未进行拷贝时,程序不会报错,正常输入,进行拷贝操作后,由于浅拷贝造成程序二次删除,进而报错,具体代码如下://一个分别对两个指针进行赋值的程序,程序正常运行
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
pvar=new int[5];
for(int i=0;i<5;i++)
{
pvar[i]=i;
}
}
~Test()
{
delete []pvar;
pvar=NULL;
}
void print()
{
for(int i=0;i<5;++i)
{
cout<<pvar[i]<<",";
}
cout<<endl;
}
private:
int *pvar;
};
int main()
{
Test t1;
t1.print();
Test t2;
t2.print();
return 0;
}运行结果:
//在主函数中进行拷贝操作,程序正常编译,运行出现中断
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
pvar=new int[5];
for(int i=0;i<5;i++)
{
pvar[i]=i;
}
}
~Test()
{
delete []pvar;
pvar=NULL;
}
void print()
{
for(int i=0;i<5;++i)
{
cout<<pvar[i]<<",";
}
cout<<endl;
}
private:
int *pvar;
};
int main()
{
Test t1;
t1.print();
Test t2;
t2.print();
t1=t2; //此处由于浅拷贝造成二次删除,从而引发中断错误
return 0;
}程序运行结果:
总结:
对象如果含有指针成员变量,而指针变量又指向堆上空间,将只拷贝指针成员变量本身的值,造成两个对象的指针指向同一块堆上的内存空间,删除对象时(含复制)会造成二次删除,进而引发程序中断
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
pvar=new int[5];
for(int i=0;i<5;i++)
{
pvar[i]=i;
}
}
~Test()
{
delete []pvar;
pvar=NULL;
}
void print()
{
for(int i=0;i<5;++i)
{
cout<<pvar[i]<<",";
}
cout<<endl;
}
private:
int *pvar;
};
int main()
{
Test t1;
t1.print();
Test t2;
t2.print();
return 0;
}运行结果:
//在主函数中进行拷贝操作,程序正常编译,运行出现中断
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
pvar=new int[5];
for(int i=0;i<5;i++)
{
pvar[i]=i;
}
}
~Test()
{
delete []pvar;
pvar=NULL;
}
void print()
{
for(int i=0;i<5;++i)
{
cout<<pvar[i]<<",";
}
cout<<endl;
}
private:
int *pvar;
};
int main()
{
Test t1;
t1.print();
Test t2;
t2.print();
t1=t2; //此处由于浅拷贝造成二次删除,从而引发中断错误
return 0;
}程序运行结果:
总结:
对象如果含有指针成员变量,而指针变量又指向堆上空间,将只拷贝指针成员变量本身的值,造成两个对象的指针指向同一块堆上的内存空间,删除对象时(含复制)会造成二次删除,进而引发程序中断
相关文章推荐
- C程序访问hadoop程序编译通过后在运行的时候出现:WARN util.NativeCodeLoader错误。
- 在windows直接运行Qt编译出来的可执行程序出现了如下提示错误: this application has requested the runtime to terminate it an unu
- 我在运行编译好的程序时,仿真器出现错误警告
- linux下编译C++程序出现错误 “*** stack smashing detected ***, eclipse解决方法
- QT程序编译无错误,运行时出现访问地址冲突
- 在windows直接运行Qt编译出来的可执行程序出现了如下提示错误: this application has requested the runtime to terminate it an unu
- VS2012运行C++程序出现fatal error LNK1104: 无法打开文件“kernel32.lib”错误
- VC 6.0 写完的程序程编译链接通过后,点运行的时候出现one or more files out of date or not exist
- 使用g++编译C/C++程序,链接时出现undefined reference to错误
- Dev-C++编译运行socket程序出现undefined reference to 'XXX@4'等消息
- gcc编译通过,但运行程序出现段错误
- java控制台编译通过,运行出现错误: 找不到或无法加载主类xx.java
- C++/Qt程序编译运行时出现的问题以及解决办法
- C程序访问hadoop出现的各种编译错误和运行时各种类DefFound异常的解决方法
- 程序Debuge版本编译通过,Release版本出现链接错误,解决办法
- vc++ 使用64位平台编译,运行程序出现0xc000007b错误的解决方案
- VC编译程序,运行时提示运行错误“由于应用程序的配置不正确,……”解决方法
- 程序Debuge版本编译通过,Release版本出现链接错误,解决办法
- VS2013的C++程序用VS2017运行,出编译错误
- 编译通过,运行出现错误:局部变量数组过大