【发布时间】:2020-04-06 09:55:25
【问题描述】:
我在一个更大的函数中使用这个类,它没有正确终止。
我不得不一次次将算法注释掉一大块,以缩小问题的起点。
整个事情都像写的那样工作,但最终错误地终止并终止了正在调用它的main()。
无论如何,当我实例化这个类时,问题就开始了。我假设它一定是析构函数的问题,当对象超出范围时导致错误。
这是类定义以及构造函数/析构函数:
class Entry
{
private:
int act_count; //number of activities for generating array MUST BE DETERMINED BEFORE INSTANTIATION
int ex_count; //number of expenditures for generating array
public:
Entry(int, int); // constructor
~Entry(); // destructor
string date; // functions like a title
Activity * act_arr; // pointer to an array of activities
Expenditure * ex_arr; // pointer to an array of expenditures
// list of member functions
};
struct Activity
{
public:
string a_name;
float time;
};
struct Expenditure
{
public:
string e_name;
float price;
};
构造函数:
Entry::Entry(int a_count, int e_count)
{
// initialization of basic members
date = day_o_year();
act_count = a_count;
ex_count = e_count;
// allocation of array space
act_arr = new Activity[act_count];
ex_arr = new Expenditure[ex_count];
}
析构函数:
Entry::~Entry()
{
// prevents memory leaks when object falls out of scope and is destroyed
delete act_arr;
delete ex_arr;
}
这里有什么严重的错误吗?我希望这不是太多的代码来引起一些兴趣。
提前致谢。
【问题讨论】:
-
这能回答你的问题吗? What is The Rule of Three?
-
我正在阅读此内容,感谢您的链接。这不在推荐帖子列表中
-
如果您使用智能指针而不是原始指针,您还应该阅读:stackoverflow.com/questions/44997955/rule-of-zero-confusion 以及它包含的链接。
-
@Richard Critten 为今晚阅读添加了书签。非常感谢。
-
使用
std::vector代替智能指针,比原来的手动分配要好得多。通过使用适当的容器,您可以避免大量代码和许多潜在问题,例如内存泄漏、原始代码可能发生的双重删除。
标签: c++ class constructor destructor