[英]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.