Listing 1: gcroot

#using <mscorlib.dll>
#using <mscorlib.dll>
#include <stddef.h>

template <class T> struct gcroot {
  typedef System::Runtime::InteropServices::GCHandle GCHandle;

  gcroot() {
    handle = GCHandle::op_Explicit(GCHandle::Alloc(0)).ToInt32();
  }

  gcroot(T t) {
  _handle = GCHandle::op_Explicit(GCHandle::Alloc(t)).ToInt32();
  }

  gcroot(const gcroot& r) {
    // don't copy a handle, copy what it points to
  _handle = GCHandle::op_Explicit(
    GCHandle::Alloc(
      GCHandle::op_Explicit(r._handle).Target )).ToInt32();
  }

  ~gcroot() {
    GCHandle g = GCHandle::op_Explicit(_handle);
    g.Free();
  _handle = 0; // should fail if reconstituted
  }

  gcroot& operator=(T t) {
    GCHandle::op_Explicit(_handle).Target = t;
    return *this;
  }

  gcroot& operator=(const gcroot &r) {
    T t = (T)r;
    GCHandle::op_Explicit(_handle).Target = t;
    return *this;
  }

  operator T () const {
    return static_cast<T>( GCHandle::op_Explicit(_handle).Target );
  }

  T operator->() const {
    return static_cast<T>(GCHandle::op_Explicit(_handle).Target);
  }

private:
        intptr_t _handle;
        T* operator& ();
};
— End of Listing —