I wonder if I would manually have to initialize it in NULL.
Yes. You must. Deleting a pointer does not put the pointer to null values.
As an analogy, imagine that the pointer is a plate and the node is spaghetti with Bolognese. When you eat the spaghetti the dish is dirty, you can use it again for another diner (another spaghetti node) putting spaghetti on the dirty dish (the other diner will not know) but if your rule is to serve only in clean dishes first you must clean it (put the plate at
Why is this happening?
One of the C ++ mantras is " do not pay for what you do not use ", which is usually interpreted as " do not do things you do not know are strictly necessary " . Erasing the content of something pointed by a pointer and putting the pointer to
NULL are two operations, the second being unnecessary because the pointer is usable whether it points to deleted data or points to
However, Bjarne Stroustrup (the creator of C ++) believes that it is a good idea that
delete reset the pointers and regrets that this idea did not become popular, here is an excerpt from your website (my translation):
If the percentage
... does not change
p the second
delete p; is a serious error that C ++ can not protect effectively (without unusual precautions). Since deleting a null pointer is harmless by definition, a simple solution would be for
delete p; to make
p = 0; after doing whatever it takes. However, C ++ does not guarantee that.
One reason is that the operand of
delete should not be a value on the left side, consider:
Here, the implementation of
delete does not have a pointer to which you can assign zero. These examples may be rare, but they make it impossible to guarantee that "any pointer to an erased object is 0". A simple way to skip this rule is to have two pointers to an object:
T* p = new T;
T* q = p;
delete q; // caramba!
C ++ explicitly allows implementations of
delete to zero a left value operand, and I hoped that implementations would do so, but this idea does not seem to have become popular among implementers.
Other things to consider.
nullptr instead of
NULL : The macro
NULL is simply the value 0, this can lead to confusing pointers with integers in some overloads, if you use the null pointer literal (
nullptr ) you will avoid that possible problem.
Use pre-increment instead of post-increment . li>