delete this

  • Thread starter Mike - EMAIL IGNORED
  • Start date
M

Mike - EMAIL IGNORED

delete this; I have seen it used occasionally,
and I would have a use for it. Is it allowed?
Assuming, of course, that I do nothing to the
object thereafter.
Thanks,
Mike.
 
T

Tomás

Mike - EMAIL IGNORED posted:
delete this; I have seen it used occasionally,
and I would have a use for it. Is it allowed?
Assuming, of course, that I do nothing to the
object thereafter.
Thanks,
Mike.

If the system called the constructor, then it's most certainly Undefined
Behaviour.

If you yourself called the constructor, well... I'd have to look at the
code.


char string_memory[ sizeof( std::string) ];

std::string* p_str = new( string_memory ) std::string;

Then somewhere on in the fable:

delete this;
 
V

Victor Bazarov

Tomás said:
Mike - EMAIL IGNORED posted:




If the system called the constructor, then it's most certainly Undefined
Behaviour.

If you yourself called the constructor, well... I'd have to look at the
code.

What "constructor"?

Mike: yes, it's perfectly fine.
char string_memory[ sizeof( std::string) ];

std::string* p_str = new( string_memory ) std::string;

Then somewhere on in the fable:

delete this;

What are you talking about?

V
 
A

Aleksander Beluga

Mike said:
delete this; I have seen it used occasionally,
and I would have a use for it. Is it allowed?

I suppose that it is OK. Think of member-functions just as about free
functions receiving this pointer.
 
B

benben

I suppose that it is OK. Think of member-functions just as about free
functions receiving this pointer.

They are trickier than you think.

Consider:

class C{
public:
void f(void){delete this;}
};

int main()
{
C c;
c.f(); // OOPS
}

Tell me what you think would happen in the line commented OOPS.

Regards,
Ben
 

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
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top