开发者

What purpose does the ~ operator have in this code?

I have digging through the C# code generated by SWIG for Quantlib and came across the following code that gave me a humbling moment.

Each of the generated classes implement IDisposable, and each of the generated classes have this convention pointed out below.

public class MultiPath : IDisposable { // MultiPath is interchangable
  private HandleRef swigCPtr;
  protected bool swigCMemOwn;

  internal MultiPath(IntPtr cPtr, bool cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = new HandleRef(this, cPtr);
  }

  internal static HandleRef getCPtr(MultiPath obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  ~MultiPath() { // <---- 
    Dispose();
  }

  public virtual void Dispose() {
    lock(this) {
      if (swigCPtr.Handle != IntPtr.Zero) {
        if (swigCMemOwn) {
          swigCMemOwn = false;
          NQuantLibcPINVOKE.delete_MultiPath(swigCPtr);
        }
        swigCPtr = new HandleRef(null, IntPtr.Zero);
      }
      GC.开发者_高级运维SuppressFinalize(this);
    }
  }
  // snip
}

If I'm reading this correctly, the bitwise complement operator is applied to the constructor of the class, so my questions are

  1. Why is the purpose of ~ operator in this example?
  2. What effect does it have?
  3. What are the correct situations to use such an operator and technique?

Edit:

Just for clarity, the ~ is this case is called a Destructor. Thanks's @Arcturus.


Its the destructor!

In simple terms a destructor is a member that implements the actions required to destruct an instance of a class. The destructors enable the runtime system, to recover the heap space, to terminate file I/O that is associated with the removed class instance, or to perform both operations.


It is short-hand for "Finalize", a non-public method that might get called by the garbage collector if you forget to call Dispose yourself.

I stress the word 'might'. Unless you do stupid things like call GC.WaitForPendingFinalizers, .NET doesn't promise you that it will actually clean up your unmanaged resoueces like pointers and database connections. This is just an extra layer of protection in case your code is screwed up.

Note the line GC.SuppressFinalize(this);. This tells the garbage collector that you remembered to call Dispose and it doesn't need to waste time running the Finalize method.


It marks the destructor of the class. Follow Destructors (C# Programming Guide) for more info.


It signifies a destructor:

Destructors are used to destruct instances of classes.

They are not used much in C# as managed resources are taken care of by the garbage collector.


that's a distructor - at least in C++, and looks like C# decided to have it unlike java that does not have it

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜