struct node
{
node(int _value, node* _next) : value(_value), next(_next) {}
int value;
node* next;
};
node *p = new node(10, NULL);
delete p;
Based on my understanding, operator delete will first call the destructor of node, then deallocate the raw memory block originally allocated for p.
Since struct node doesn’t provide a customized destructor, the compiler will provide a default one.
Question1>what does the default destructor look like?
For example,
node::~node()
{
next = NULL;
}
Question2>should we define a destructor for struct node or not?
I assume that we don’t have to explicitly provide such a destructor. The reason is that the member variable next doesn’t own the pointed resource and it behaves as a weak_ptr. Is that correct?
Sounds correct to me.
Because
struct nodeis a “Plain Old Datatype” the compiler won’t actually create any destructor code at all, there’s no need to specially destruct ints or pointers.Even for non-POD types, the compiler default destructor will just take the form:
Individual members will still have their destructors called, but if you didn’t allocate any non-automatic resources, you generally don’t need to provide a destructor. There are situations where you might, but they’re somewhat special purpose.
You may want to refer to this question on the rule of three.