gpt4 book ai didi

c++ - 从复制构造函数调用构造函数时,它也会调用析构函数

转载 作者:行者123 更新时间:2023-11-30 01:42:19 25 4
gpt4 key购买 nike

我编写了一个使用复制构造函数复制对象的程序。在复制构造函数中,我调用了构造函数来创建内存并复制内容。它在构造函数中成功完成,但在构造函数结束后立即调用析构函数,我得到了垃圾值。最后在主函数中,如果我试图破坏新创建的对象,程序就会崩溃。为什么会这样?

这是代码。

#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]); 只是创建一个临时的 Test,它将立即被销毁。 Test 的所有成员都没有被初始化。

你想要delegate constructor ,这是一个 C++11 特性。

Test(const Test &ob) : Test(ob.a, ob.p[0], ob.p[1])
{
cout<<"\n\n "<<this->a<<" "<<this->p[0]<<" "<<this->p[1];
}

关于c++ - 从复制构造函数调用构造函数时,它也会调用析构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39775889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com