Original Post
What happens if I do "delete this;" inside a function? will it erase itself? Thanks.
long release_() { if ( !--m_refCount ) { on_final_release(); delete this; return 0; } return m_refCount; }void F(Obj* this) { // do whatever with this delete this;}Quote:
From [16.15] Is it legal (and moral) for a member function to say delete this?:
As long as you're careful, it's OK for an object to commit suicide (delete this).
Here's how I define "careful":
You must be absolutely 100% positive sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new).
You must be absolutely 100% positive sure that your member function will be the last member function invoked on this object.
You must be absolutely 100% positive sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members).
You must be absolutely 100% positive sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it.
Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class when you don't have a virtual destructor.
class foo { foo( int i ) : refcount( 1 ) {}public: static foo * create( int i ) { return new foo( i ); } void release( void ) { if (!--refcount) delete this; }private: unsigned refcount;};int main () { foo * object = foo::create( 42 ); //OK object->release(); //OK foo local_object( 42 ); //illegal: ctor is private}foo global_object( 42 ); //illegal: ctor is privatefoo * direct_new_object = new foo( 42 ); //illegal: ctor is privateThis topic has been locked by a moderator. New replies are not allowed.
With your permission, GameDev.net uses analytics cookies to understand how people use the platform. You can accept analytics or continue with necessary cookies only. Learn more