Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c++ - "delete this" in constructor

What actually happen when I execute this code?

class MyClass
{
    MyClass()
    {
        //do something
        delete this;   
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Note: This answer applies to C++03, and it seems like the behavior was changed in C++11 and higher so that this is now undefined behavior.

It turns out that in this particular case the code is legal, but you're ε-away from undefined behavior.

The C++03 standard defines the notion of the "lifetime" of an object to be the time between which its constructor has finished running and when the destructor starts running. It also explicitly states (in §3.8/5) that

Before the lifetime of an object has started [...] If the object will be or was of a class type with a non-trivial destructor, and the pointer is used as the operand of a delete-expression, the program has undefined behavior.

Since an object's lifetime has not started until the constructor finishes, inside the constructor the this pointer you've referred to has not begun its lifetime, trying to delete it in this case is totally safe. However, if you write a destructor for the class, then you'll immediately run into undefined behavior here.

In addition, if you change the constructor so that you try referencing any of the class's data members after you delete the object, you'll get undefined behavior. If the object was allocated on the stack, you'll get undefined behavior. If the object was static, you'll get undefined behavior. If the object was allocated using new, then the pointer the client will get back to it will be invalid and using it will result in undefined behavior. In general, don't try doing this!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...