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
- Why is the purpose of
~
operator in this example? - What effect does it have?
- 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.