delete(this)

R

Rahul

Hi Everyone,

I was wondering what the standard says about the following,

class test
{
public: test()
{
delete(this);
}
~test()
{
delete(this);
}
};

int main()
{
test object;
}

Thanks in advance!!!
 
R

Rolf Magnus

Rahul said:
Hi Everyone,

I was wondering what the standard says about the following,

class test
{
public: test()
{
delete(this);
}
~test()
{
delete(this);
}
};

int main()
{
test object;
}

It says that this code has undefined behavior. You must not delete objects
that haven't been created using new.
 
P

peter koch

Hi Everyone,

 I was wondering what the standard says about the following,

class test
{
 public: test()
            {
               delete(this);
            }
           ~test()
            {
              delete(this);
           }

};

int main()
{
 test object;

}

 Thanks in advance!!!

This is full of undefined behavior, the first one being destruction of
an object that had not yet been fully constructed, the second being
calling delete on something not allocated by new, and the third being
calling the destructor on the same object twice. There might be more,
but technically the first one is all you can talk about,

/Peter
 
J

James Kanze

Rahul wrote:
It says that this code has undefined behavior. You must not
delete objects that haven't been created using new.

Amongst other things. Think of what will happen in a new
expresssion: "new test". I don't think deleting the return
value of new is really a good idea either. And of course, if
you call delete on a pointer to test, you'll end up double
deleting.

Delete this is pretty much a standard idiom, but not from the
constructor or the destructor.
 
J

James Kanze

I wonder if that could cause an infinite loop with some compilers.

An infinite loop, only if the compiler does tail recursion
optimization, but an infinite recursion does seem likely, since
the first thing a delete expression does is call the destructor.

Well spotted.
 

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,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top