Partager via


How to: Use safe_cast and Boxing

Boxing in defined as a compiler-injected, user-defined conversion. Therefore, safe_cast can be used to box a value on the CLR heap.

The following sample shows boxing with simple and user defined value types. A safe_cast will box a value type variable that is on the native stack so it can be assigned to a variable on the garbage-collected heap.

Example

// safe_cast_boxing.cpp
// compile with: /clr
using namespace System;

interface struct I {};

value struct V : public I { 
   int m_x;

   V(int i) : m_x(i) {}
};

int main() {
   // box a value type
   V v(100);
   I^ i = safe_cast<I^>(v);

   int x = 100;
   V^ refv = safe_cast<V^>(v);
   int^ refi = safe_cast<int^>(x);
}

The following sample shows that boxing has a higher priority over a user-defined conversion in a safe_cast operation:

// safe_cast_boxing_2.cpp
// compile with: /clr
static bool fRetval = true;

interface struct I {};
value struct V : public I {
   int x;

   V(int argx) {
      x = argx;
   }

   static operator I^(V v) {
      fRetval = false;
      I^ pi = v;
      return pi;
   }
};

ref struct R {
   R() {}
   R(V^ pv) {}
};

int main() {
   V v(10);
   I^ pv = safe_cast<I^>(v);   // boxing will occur, not UDC "operator I^"
}

See Also

Reference

safe_cast