override delete operator to set to NULL

M

Mathieu Malaterre

Hello,

I am trying to override the delete operator so that it set 0 to my
object. Is this possible ?

I am used to do:

obj *a = new obj;
....
delete a;
a = 0; //prevent any misuse.

But I am looking for a transparent way to do it.

Thanks,
Mathieu
 
G

Gregg

Hello,

I am trying to override the delete operator so that it set 0 to my
object. Is this possible ?

I am used to do:

obj *a = new obj;
...
delete a;
a = 0; //prevent any misuse.

But I am looking for a transparent way to do it.

Thanks,
Mathieu

This would be of dubious value since you can have multiple variables
pointing to the same object, and you would also have to handle the case
where the pointer is not even stored in a variable at all, e.g.

delete ptr + 1;

If you still wanted to go ahead with the idea, you probably can't do it
by overloading operator delete. You would have to introduce a smart
pointer type that overrides ->.

Gregg
 
P

Phlip

Mathieu said:
I am trying to override the delete operator so that it set 0 to my
object. Is this possible ?

I am used to do:

obj *a = new obj;
...
delete a;
a = 0; //prevent any misuse.

The need to set a pointer to NULL, after delete, is a C++ "Design Smell".
That means when you notice it, you have an indicator of poor design
elsewhere.

In this case, how can you contrive to make your 'a' _always_ go out of scope
just after deleting it? Going out of scope and disappearing is the best way
a variable has to prevent others from messing with it.

(Hint: Look up "Resource Acquisition Is Initialization".)
 
D

Daniel T.

Mathieu Malaterre said:
I am trying to override the delete operator so that it set 0 to my
object. Is this possible ?

I am used to do:

obj *a = new obj;
...
delete a;
a = 0; //prevent any misuse.

But I am looking for a transparent way to do it.

template < typename T >
void DELETE( T*& p ) {
delete p; p = 0;
}

template < typename T >
void DELETE_ARRAY( T*& p ) {
delete [] p; p = 0;
}

However, you would be far better off to use a smart pointer:

auto_ptr<obj> a( new obj );

// now you don't have to delete it and don't have to
// worry about preventing misuse, after it is deleted.
 

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

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top