Skip to main content
gamedev.net
🔒 Locked

C++ Object existence

Started by Thomo 2 replies 750+ views
Original Post
Thomo
Thomo
I have created a custom class and created an object of that class using 'new. Later, I 'delelete' the class. Further I need to know when the object no longer exists so I have tried the following: cThing pThing = new cThing . . . delete this [pThing] if (pThing) { do this } This doesn't work. Can someone tell me how do it correctly. Thanks.
Bregma
Bregma
In general, you just have to design your program correctly so that this problem doesn't happen. There is not way to do what you're asking.

There are circumstances in which you can set your pointer to zero after deleting the object it points to. This will hide certain types of errors, but in general is a useless practice that just hides certain types of errors and makes it less obvious where your serious design flaws are.

--smw
Stephen M. Webb
Professional Free Software Developer
Emmanuel Deloget
Emmanuel Deloget
Quote:
Original post by Bregma
In general, you just have to design your program correctly so that this problem doesn't happen. There is not way to do what you're asking.

There are circumstances in which you can set your pointer to zero after deleting the object it points to. This will hide certain types of errors, but in general is a useless practice that just hides certain types of errors and makes it less obvious where your serious design flaws are.

--smw


Trueness inside.

@Thomo: there's a "why do you want to do this?" in your question, because most of the time what you want to do is a clear sign of a design error.

However, if you can't just correct the design error, this code will help:
// take care: the parameter is a reference to a pointertemplate <class T> void delete_null(T*& p){  delete p;  p = NULL;}

Instead of calling delete p;, you now call delete_null(p). Later, you simply test for the nullity of the pointer to test whether it is a valid pointer or not.

But I really encourage you to find another way to handle this issue. Do you have any other information which could help us to devise a solution with you?
JohnBolton
JohnBolton
The basic problem is that C++ does not automatically keep track of what every pointer points to. One possible solution is to use boost::shared_ptr and boost::weak_ptr. Your example has another complication though -- it does delete this. That is usually not a good thing to do, so perhaps you can fix your problem by getting rid of the delete this.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.