Newsflash: C++ object commits sepuku

Check this out. Is it valid C++?

class X {
  void dispose() {
    delete this;
  }
};

Strange pattern, isn’t it?. What happens if you try to dispose a heap object?

void f() {
   X x;
   x.dispose();
}

Indeed, nasal demons FTW, you’re trying to free an invalid pointer. Yet if we change that a little bit…

void f() {
   (new X)->dispose();
}

Zomg now it works. It’s weird, but it works. Why would anybody on earth do something like this? Can you guess when would this be useful?

Some times you launch a background job, and you don’t really care when it’s done. You may use a callback to be notified when the job is done, but if you don’t really care then having an object which deletes itself is an option. You’ll have to be very careful about it, though, because this is legal C++ too:

class X {
  void dispose() {
    delete this;
    std::cout << "Hello worldn";
  }
};

Though “Hello world” will be printed, it will be running in a dead object. Which is fine, as far as the compiler cares, but if you do try to reference the this pointer, you’ll be in a lot of trouble.

Bonus reading
For a much more interesting note than mine, go and check When does an object become available for garbage collection? in The Old New Thing.

Advertisements

One Comment on “Newsflash: C++ object commits sepuku”

  1. […] Now, in this new “translated” code, what do you think? Will it crash? It won’t, since no one is going to dereference “this”. Crazy, huh? This crazy idiom also allows even crazier things, like C++ objects committing sepuku […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s