【发布时间】:2017-02-08 02:37:22
【问题描述】:
我制作了一个使用复制构造函数复制对象的程序。在复制构造函数中,我调用了构造函数来创建内存并复制内容。它在构造函数中成功执行此操作,但在构造函数结束后立即调用析构函数,我得到垃圾值。最后在主函数中,如果我尝试破坏新创建的对象,程序就会崩溃。为什么会这样?
这是代码。
#include<iostream>
using namespace std;
class Test
{
public:
int a;
int *p;
Test(int a,int b,int c)
{
this->a=a;
p=new int[2];
p[0]=b;
p[1]=c;
cout<<"\n\n "<<this->a<<" "<<this->p[0]<<" "<<this->p[1];
}
Test(const Test &ob)
{
Test(ob.a,ob.p[0],ob.p[1]);
cout<<"\n\n "<<this->a<<" "<<this->p[0]<<" "<<this->p[1];
}
void print()
{
cout<<"\n\n\n "<<a<<" "<<p[0]<<" "<<p[1];
}
~Test()
{
cout<<"\n\n\n DESTRUCTOR CALLED "<<endl;
delete [] p;
}
};
int main()
{
Test *ob1=new Test(2,3,4);
cout<<"\n\n\n ob2: new object";
Test *ob2=new Test(*ob1);
cout<<"\n\n\n ob1";
(*ob1).print();
cout<<"\n\n\n ob2";
(*ob2).print();
delete ob1;
delete ob2;
return 1;
}
产生输出:
2 3 4
ob2: 新对象 2 3 4
调用了析构函数
9968956 9968956 0
ob1
2 3 4
ob2
9968956 9968956 0
调用了析构函数
调用了析构函数
“然后程序停止工作,即崩溃”......
我了解在这种情况下会发生什么,但请解释一下为什么在删除对象 ob2 时程序会在这种情况下崩溃。 谢谢
【问题讨论】:
-
您真正想用
Test(ob.a,ob.p[0],ob.p[1]);实现什么?对我来说听起来像是一个 XY 问题。 -
p=new int(2*sizeof(int));是做什么的?你的意思可能是p=new int[2];。
标签: c++ c++11 constructor copy-constructor