我有这个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];
}
};
Run Code Online (Sandbox Code Playgroud)
(我知道把它变成一个类可能会更好,但让我们考虑一下它).
我不太确定我是否为此编写了正确的析构函数.在main函数中我使用的是根节点:
Node *root = new Node();
Run Code Online (Sandbox Code Playgroud)
虽然代码不会泄漏内存(只要你delete在根节点中main),但它并不是真正的最佳选择.
你应该避免new和delete,而是更喜欢智能指针.在这种情况下,使用unique_ptr.
另外,不要在堆上创建根节点,只需正常创建它:
Node root;
// use root normally
Run Code Online (Sandbox Code Playgroud)
您也没有正确遵循五条规则,如果您使用unique_ptr过,您甚至不需要担心,因为您没有自定义dtor.但也没有理由采取c和ind通过ref和const 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();
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
590 次 |
| 最近记录: |