c++ 复制构造函数和析构函数
c++ Copy constructors and destructors
我正在学习 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;
}
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在c++中使用向量时,如何调用构造函数和析构函数
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 不命名构造函数和析构函数上的类型错误
- 在 UML 类图中为C++类添加构造函数和析构函数
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 为什么类构造函数为其成员生成析构函数?
- makefile对我的名称空间对象/函数/构造函数的不确定引用
- 没有可调用的匹配函数(构造函数),候选函数不同于对给定类型的引用
- C++库制作,隐藏在标头中没有友元的析构函数/构造函数
- 从另一个成员函数/构造函数调用C++构造函数是否执行初始值设定项列表
- 在另一个函数/构造函数 [C++] 中初始化后使变量只读
- std::调用函数时找不到函数构造函数
- 显式调用基类析构函数/构造函数合法吗
- 函数构造函数和nullptr
- 用委托构造函数构造函数
- 虚函数构造函数和调用虚函数时会发生什么
- 一些Qt函数/构造函数参数的内存管理
- 使用for_each或std::transform时,c++函函数构造函数是如何被调用的?
- std函数构造函数初始化