Search code examples
c++pointersdelete-operator

Should I delete a pointer to an int in a class's deconstructor (in C++)?


I'm really having a hard time understanding pointers, so please forgive me for any ambiguity this question may have. Yes, I'm asking more than one question, the one in the title is by far the most important, though. The other questions are just questions that I would really appreciate you answering. So lets say I have a class which looks something like this:

class myclass
{
public:
    myclass();
    ~myclass();
private:
    struct node
    {
        node * next;
    }
    node * head;
    int myint;
}

Now, as I'm aware, one would call constructors for the class and struct, as well as deconstructors for each. I've been told that integers shouldn't be deleted in the deconstructor, but what about deleting the pointer to the integer. Shouldn't that be deleted in the deconstructor like this:

myclass::~myclass
{
    delete head;
    delete &myint;
}

If not, why?

If you want to just answer that question, read no further. For the sake of brevity, my next question is about this code, and the deconstructor above, which I've been told is wrong (assume this is part of the same file as the deconstructor above):

myclass::node::~node
{
    delete next;
}

More specifically, I've been told I shouldn't delete nodes unless they've been declared with a new tag. Needless to say, I find that very confusing. If you can, could you explain what they mean by that and why what they're saying is true? A link explaining that would be equally appreciated, just understand that I'm new to coding, I just started learning C++ a few months ago.


Solution

  • You can only use delete on memory that was allocated dynamically using new.

    In your case, myint is not a separate block of dynamically allocated memory. It's a member of the myclass object, and its memory cannot be managed separately from the containing object. When you allocate a myclass object (either as an ordinary variable, or dynamically using new myclass), all its members will be allocated; when you free it, all its memory will be reclaimed. You don't need to delete the individual members.