[英]Is this a correct destructor for my Node struct?
我有这个C ++结构:
struct Node {
char symbol;
unsigned int index;
vector<Node*> next;
// Constructors
Node():symbol('$'), index(0), next(0) {}
Node(char &c, const unsigned int &ind):symbol(c), index(ind), next(0) {}
// Add a new character
Node* add(char &c, const unsigned int &num) {
Node *newChar = new Node(c, num);
next.push_back(newChar);
return newChar;
}
// Destructor
~Node() {
for (int i = 0; i < next.size(); i++)
delete next[i];
}
};
(我知道最好将它设为一个类,但让我们按原样考虑)。
我不确定是否为此编写了正确的析构函数。 在主要功能中,我使用了根节点:
Node *root = new Node();
尽管代码不会泄漏内存(只要您delete
main
的根节点),但这并不是最佳选择。
您应该避免使用new
和delete
,而应该使用智能指针。 在这种情况下,请使用unique_ptr
。
另外,不要在堆上创建根节点,只需像下面这样正常创建它:
Node root;
// use root normally
您也不会正确地遵循5的规则,如果您使用unique_ptr
,则甚至不必担心它,因为您将没有自定义dtor。 也没有理由通过ref
和const ref
来接受c
和ind
,只按值传递它们(因为您甚至都没有更改它们,并且按值传递值与对原语的ref一样便宜)。
经过这些更改,代码如下所示
struct Node {
char symbol;
unsigned int index;
vector<std::unique_ptr<Node>> next;
// Constructors
Node():symbol('$'), index(0){}
Node(char c, unsigned int ind):symbol(c), index(ind) {}
// Add a new character
Node* add(char c, unsigned int num) {
next.push_back(std::make_unique<Node>(c, num));
return next.back().get();
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.