简体   繁体   English

这是我的Node结构的正确析构函数吗?

[英]Is this a correct destructor for my Node struct?

I have this C++ 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];
    }
};

(I know it might be better to make it a class but let's consider it as it is). (我知道最好将它设为一个类,但让我们按原样考虑)。

I'm not quite sure if I wrote the correct destructor for this. 我不确定是否为此编写了正确的析构函数。 In the main function I'm using a root node: 在主要功能中,我使用了根节点:

Node *root = new Node();

Although the code won't leak memory (as long as you delete the root node in main ), it isn't really optimal. 尽管代码不会泄漏内存(只要您delete main的根节点),但这并不是最佳选择。

You should avoid new and delete and instead prefer smart pointers. 您应该避免使用newdelete ,而应该使用智能指针。 In this case, use unique_ptr . 在这种情况下,请使用unique_ptr

Also, don't create the root node on the heap, just create it normally like so: 另外,不要在堆上创建根节点,只需像下面这样正常创建它:

Node root;
// use root normally

You also don't follow the rule of five properly, and you won't even need to worry about it if you used unique_ptr since you wouldn't have a custom dtor. 您也不会正确地遵循5的规则,如果您使用unique_ptr ,则甚至不必担心它,因为您将没有自定义dtor。 There's also no reason to take the c and ind by ref and const ref , just pass them by value (because you don't even change them, and its as cheap passing by value as by ref for primitives). 也没有理由通过refconst ref来接受cind ,只按值传递它们(因为您甚至都没有更改它们,并且按值传递值与对原语的ref一样便宜)。

With these changes, the code looks like this 经过这些更改,代码如下所示

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM