c++ 复制构造函数和析构函数

c++ Copy constructors and destructors

本文关键字:析构函数 构造函数 复制 c++      更新时间:2023-10-16

我正在学习 c++ 中的构造函数和析构函数;帮助我抓住我的错误,即使它们是愚蠢的......

这是我编写的代码,用于使用 c++ 中的类执行加法;这将创建数据类型为 num 的两个总和,并使用构造函数sum((来执行两个数字的总和;然而,当一切顺利时,我偶然发现了为 num 创建了一个复制构造函数,(虽然不是必需的,但仍然用于实践(......没有类sum的动态对象,无论如何都不可能运行代码(不删除复制构造函数(...帮助我改进我的代码和我在下面代码中的错误;我还想知道如何在这个程序中使用复制构造函数;问题是在析构函数中,删除操作在同一块内存上多次执行(我想(

这是我的代码

#include<iostream>
#include<new>
using namespace std;
class num
{
public:
int *a;
num(int x)
{
try
{
a=new int;
}
catch(bad_alloc xa)
{
cout<<"1";
exit(1);
}
*a=x;
}
num(){  }
num(const num &ob)
{
try
{
a=new int;
}
catch(bad_alloc xa)
{
cout<<"1''";
exit(2);
}
*a=*(ob.a);
}
~num()
{ 
cout<<"Destruct!!!";
delete a;
}
};

class sum:public num
{
public:
int add;
sum(num n1,num n2)
{
add=*(n1.a)+*(n2.a);
}
int getsum()
{
return add;
}
};
int main()
{
num x=58;
num y=82;
sum *s=new sum(x,y);
cout<<s->getsum();
delete s;
return 0;
}

我可能会错过一些东西 - 没有使用new/delete太久,但试图纠正我注意到的所有内容。

附言始终使用智能指针。

#include <iostream>
#include <exception>
#include <new>
using namespace std;
int* allocate(const char* err_msg, int exit_code)
{
int* a = nullptr;
try
{
a = new int;
}
catch (bad_alloc&)
{
cout << err_msg << endl;
exit(exit_code);
}
return a;
}
class num
{
int* a = nullptr; // always should be initialized here
public:
num() noexcept : a(nullptr) // or here
{}
/*explicit*/ num(int x) : a(allocate("1", 1))
{
*a = x;
}
num(const num& ob) : a(allocate("1''", 2))
{
*a = *(ob.a);
}
// rule of zero/three/five
// default copy assignment will copy pointer and one int will be leaked and one will be deleted twice
num& operator =(const num& ob)
{
if (&ob == this)
{
return *this;
}
*a = *(ob.a);
return *this;
}
~num()
{ 
cout << "Destruct!!!";
delete a;
a = nullptr; // usefull for debug
}
int value() const
{
if (a == nullptr)
{
throw runtime_error("a == nullptr");
}
return *a;
}
};
class sum
{
int add = 0;
public:
sum(const num& n1, const num& n2)
{
add = n1.value() + n2.value();
}
int getsum() const
{
return add;
}
};
int main()
{
const num x = 58;
const num y = 82;
const sum* s = new sum(x, y);
cout << s->getsum() << endl;
delete s;
return 0;
}