Thursday, 24 July 2008

Managed-wrapped unmanaged wrapper

A quick post to show a C++/CLI template for containing an unmanaged resource RAII instance variable in a managed object that uses the destruction pattern in my earlier post.

template<typename T>
ref class NWrap sealed {
 int disposed;
 T* const obj;
 !NWrap() { delete(obj); }
public:
 explicit NWrap(T const& src) : obj(new T(src)) {}
 ~NWrap() {
  if (System.Threading.Interlocked.
           CompareExchange(disposed, 1, 0))
   return;

  this->!NWrap();
 }
};

Your RAII class must by copyable (or support auto_ptr style move). This can then be used as

NWrap<raii_type> membername;
and initialised from a constructor initialiser as:

: membername(raii_type(args...)) {}

No comments: