delete this;

Is this a terrible idea?

I have C entry points into a C++ applications. The child classes should be used like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
MyClass* g_mod;
MY_API void init()
{
    g_mod = new MyClass();
}

MY_API void step()
{
    g_mod->step();
}

MY_API void exit()
{
    delete g_mod;
}


Now if the program is killed before init() is complete, then exit() will be called and g_mod will not have been initialized which will be a not-so-clean end to the program.

Since MyClass is always dynamically allocated pointer, is this a completely insane solution?
1
2
3
4
5
MyClass
{
    //...
    ~MyClass() { delete this; } // leave exit() empty.
}
Last edited on
If MyClass's dtor is running... it has already been deleted... so yes that is a terrible idea.

Furthermore there is no way (from that) to guarantee that MyClass was created on the heap and therefore SHOULD be deleted (ie: if you put it on the stack, you must not delete it!)


EDIT:

any reason you can't use RAII? You really should use it whenever you're doing dynamic allocation and/or manual resource management.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
typedef std::unique_ptr<MyClass> MyClassPtr;
MyClassPtr g_mod;

MY_API void init()
{
    g_mod = MyClassPtr( new MyClass() );
}

MY_API void step()
{
    g_mod->step();
}

MY_API void exit()
{
    g_mod.reset();
}
Last edited on
~MyClass() { delete this; }
stack overflow


┬┐why is `g_mod' a pointer?
@Disch Ooo, didn't think of std::unique_ptr. Helpful as always, thanks.

@ne555 these are pointers so that I can control in what order the objects are created There are several instances of MyClass* each with their own explicit entry points and if I define these in the global scope without pointers, I can't control which order they get created.
Last edited on
@Disch Ooo, didn't think of std::unique_ptr


It should be your first thought.

Learn to love RAII. Embrace it. Cherish it. =)
Last edited on
Topic archived. No new replies allowed.