Re: Question Regarding Pointers
"someone" <born.2be.wyld@gmail.com> wrote in message
news:1148525967.176010.143400@g10g2000cwb.googlegroups.com...
Hey All:
I have two pointers A & B pointing towards data objects C & D resp. Now
I want to achieve the following:
1. Free up memory that A points to
The problem here is who "owns" the data, C or A? So if you had done this:
MyObject* C = new MyObject();
A = C;
it would make more sense to delete C since C "owns" the memory. But, if you
have C not "own" it anymore, perhaps you do:
C = NULL;
Then A is the only one with a pointer to the memory so A "owns" it.
Reguardless, the syntax is:
delete A;
or
delete C;
which frees up the memory A (or C) points to that was allocated without
changing where A (or C) is pointing to, so it points to memory that is no
longer valid.
of course, if the object A points to wasn't allocated with new, you dont'
want to use delete. If it was allocated with malloc, you use free. If it
was dynamically created don't do anything. I.E.
MyObject C;
A = &C;
A points to object C, but you dont' need to free the memory. It will
automatically be freed when C goes out of scope (making A point to invalid
memory).
2. Have A point towards D
if D is a pointer:
A = D;
if D is an instance:
A = &D;
&D means the address of D.
3. Have B point to nothing.
B = NULL;
Some people would argue that this isn't a good idea, some would argue that
it is. It all depends on why you want it to point to nothing. It is safe
to delete a NULL pointer, however.
MyClass* B = new MyClass();
delete B;
delete B; // Error, B points to memory that was already freed.
MyClass* B = new MyClass();
delete B;
B = NULL;
delete B; // Does nothing. Deleting a null pointer is safe and nothing is
actually done.
How could this be implemented efficiently?