Home > OS >  Exclamation mark in C /CLI
Exclamation mark in C /CLI

Time:12-12

I was reading this article by Microsoft on how to marshal managed classes to native and the other way round, and I came across these lines:

  • this->!context_node();
  • protected:
      !context_node()
      {
        // method definition
      }
    

I searched on Google and StackOverflow for the meaning of exclamation mark (!) in the above pieces of code, but I found nothing about it and so I'm asking here if anyone can shed a light on this.

Thanks in advance to anyone that will answer.

CodePudding user response:

!classname() is the finalizer.

Since these are managed classes, their lifetime is controlled by the garbage collector.

If you implement a method ~classname(), that's the Dispose method because it's C /CLI. It's not the destructor like in plain C . If you implement it, the compiler automatically makes your class implement IDisposable, and calls to delete from C /CLI or to Dispose in C# will call that method.

If you implement a method !classname(), that's the Finalizer. The Garbage Collector will automatically call that method when it cleans up that object.

In the example you linked to, they also had this:

public:
  ~context_node()
  {
    this->!context_node();
  }
protected:
  !context_node()
  {
    // (Step 7) Clean up native resources.
  }

So, this is a Dispose method (~), which calls the Finalizer method (!) explicitly, so that there's no code duplication. This way, one can either call delete explicitly (or use stack semantics, same thing), or wait for the garbage collector to clean it up, and either way, the native resources will be cleaned up properly. If you had any managed resources you'd clean those up in the Dispose method only, not in the finalizer. (The C /CLI compiler knows how to implement the IDisposable pattern properly, so it knows to suppress the finalizer if the Dispose method was called.)

  • Related