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:
Wow, talk about ambiguity…
Yep, it is kinda unnerving when that sort of bug hits you 🙂
Wow, what a terrible way to code. Even if it had comments, it still kinda sucks.
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.
@Guess Who
How exactly is it a terrible way to code?
@Vikram
In C++/CLI, the destructor is implemented using the Dispose pattern. So the destructor and finalizer are two separate entities.
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 !
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