A finalizer that nearly ended up wrong!

Holy cow! I very nearly wrote some messed up code a few minutes ago. I was writing this disposable class, and I wanted to call the finalizer from my destructor, to avoid code duplication. Guess what I did first! Man, I really was stupid! Here goes.

~MyType()
{
    !MyType();
}

And you know what that code does, don’t you? It constructs a new object and calls the logical Not operator on it! 😳

This was what I meant to do.

~MyType()
{
    this->!MyType();
}

Geez! That’s the sort of bug that could easily have slipped past me, and I wouldn’t have known for a long time. :hmmm:

Advertisements

8 thoughts on “A finalizer that nearly ended up wrong!

  1. Umm, Nish, sorry if this question sounds silly, but what does this->!MyType() do? IIRC, the destructor *is* the finalizer, at least in C#.

    Cheers,
    Vikram.

  2. I am new to C#, C++. What’s the difference between a finalizer and a destructor ? I thought the C# version of destructor is a finalizer . And why would one wish to call a destructor from a finalizer, if they are both semantically the same ?

    Sorry for the naivette !

  3. Or you could have refactored the code in the finalizer to a separate method and called that
    method from both the destructor and the finalizer().

    Cheers
    Ashley

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