简体   繁体   中英

When do I need to delete pointers, and when do I need to set them to 0?

I'm a CS student learning about C++.

This is a general question, but the particular example I'm working with is making a linked list that will have nodes to store string pointers.

class LinkNode {
public:
    friend class Stack;
    LinkNode* next;
    std::string* data;
    LinkNode(std::string* data, LinkNode* next) :data(data), next(next) { ; }
}

If I'm using pointers, then shouldn't I have a destructor that calls delete on both the next and data ?

~LinkNode() {
    delete this->data;
    delete this->next;
}

The code used in my educational material as well as samples across the internet all neglect to include this (even though we do use destructors in other contexts). I'm trying to understand why this would not be required in this case.

And, quite relatedly: if I'm using a pointer to delete something, do I have to set the pointer to null?

I often see people write a deletion out like this this:

delete ptr;
ptr = 0;

From what I understand the purpose of setting it to 0 is just to prevent it from being accidentally used, as after the delete it now points to an invalid memory address.

So if I'm calling delete at the end of a function where the pointer will fall out of scope anyway, like in a pop function or the destructor, can I omit that line? Do people just include it out of habit?

  • delete pointers pointing to a valid object/variable to destroy them and free space.
  • Set them to NULL , nullptr or 0 (quite the same) so you can identify them as unused.

You see, if you just delete the object, the pointer itself doesn't change , so now it's pointing to a invalid space of memory. If you are never again going to use that pointer, then that's not a big deal, but otherwise it could be very problematic.

So setting it to null allows you to perform checks on your pointer and be sure whether your pointer is being used or not.


Also, to answer as your first question, and as pointed out in the comments, you have to call delete on the pointers that you have created with new .

  • So, let's say that the data pointers of your example point to a string created outside of the list (so it behaves like a list of references). In that case that pointer is not in charge to manage its content and should not be deleted.
  • But if, for example, each time you add a new node, you did data = new string("whatever"); , then yes, you should delete them in the destructor.

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