proper deletion of pointers

  • Thread starter Dwight Army of Champions
  • Start date
D

Dwight Army of Champions

Why are you supposed to set a pointer equal to zero after deleting it?
At what times are you not supposed to do this? I've been using "delete
x; x = 0;" all the time, so often, in fact, that I just put them both
on the same line. If you are supposed to do this every time, then why
bother having two separate commands?
 
D

Dwight Army of Champions

I see. But why would you ever use the pointer again? To point to
another object? Why not just define and initialize another pointer,
then?
 
T

tonydee

I see. But why would you ever use the pointer again? To point to
another object? Why not just define and initialize another pointer,
then?

As an example, say you have a string class that allocated space for
the text on the heap. When empty, the pointer can be 0. So, someone
might do something like:

my_string s;
s = "abc";
s.clear();
s = "xyz";

And you could implement this quite cleanly by newing the memory in
operator=(), then deleting it in clear(). The destructor can just
delete the pointer, not caring whether it's 0 or not, as deleting a 0
pointer is a "no-operation".

Hope that helps,
Tony
 
M

Michael Tsang

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Why are you supposed to set a pointer equal to zero after deleting it?
At what times are you not supposed to do this? I've been using "delete
x; x = 0;" all the time, so often, in fact, that I just put them both
on the same line. If you are supposed to do this every time, then why
bother having two separate commands?

The pointer deleted may not be writable:

class foo_t {
public:
int *const ptr;
foo_t() : ptr(new int) {
}
~foo_t() {
delete ptr; // ptr is read only
}
};
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkuCoA0ACgkQm4klUUKw07AYoQCfY+XGNXTbwt6DmZtKQFjem2oY
FcwAnjoggWcVldlaJ8M597rD4I4V9WfS
=3O5X
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top