简体   繁体   中英

Is this a correct destructor for my Node struct?

I have this C++ struct:

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.

You should avoid new and delete and instead prefer smart pointers. In this case, use 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. 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).

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();
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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