7 __gc Pointers

7 __gc Pointers

Visual Studio .NET 2003

The common language runtime maintains a separate heap on which it implements a precise, asynchronous, compacting garbage collection scheme. To work correctly, it must track all storage locations that can point into this heap at runtime.

Since regular C++ pointers are impossible in general to track precisely, __gc pointers are introduced. They are the pointers whose variables are known to the common language runtime garbage collector. The rules for casting __gc pointers are much stricter than those of standard C++ pointers.

Note   Unsafe pointer operations are very dangerous when using a compacting garbage collector scheme. A pointer that points to a random place in the common language runtime heap is far more likely to cause problems than a random pointer in the C++ runtime heap. The Managed Extensions are designed to protect the integrity of pointer types, in order to minimize heap failures.

The common C++ idiom of using a void* pointer to point to an arbitrary object is replaced by Object*, which can hold a pointer to an arbitrary __gc class.

Similarly System::Void * can be used to point to an arbitrary value class.


  • The keywords __gc and __nogc can be used to explicitly specify whether a pointer can or cannot point into the common language runtime heap, respectively. They are left-modifiers, meaning they appear to the left of the pointer operator they modify. They are left-modifiers to avoid ambiguity with __gc applied to array brackets.


// __gc_pointers.cpp
// compile with: /clr
#using <mscorlib.dll>

__value struct V { int i; };
__gc struct G { V v; };

int main() {
   G __gc* pG = new G;   // pG can point into common language runtime heap
   V __gc* pV = &pG -> v;   // pV can point into runtime heap
   V v;
   V __nogc* pV2 = & v;   // pV2 cannot point into runtime heap 
   int __gc*  gcpi = & pV -> i;   // gcpi can point into runtime heap
   int __nogc* pi = & pV2 -> i;   // pi cannot point into runtime heap
  • The compiler and runtime work together to zero-initialize all __gc pointers before the user program or garbage collector can access them. The user does not have to initialize them to zero.
  • A __gc pointer to an object of __value class type can either point into the stack or into the common language runtime heap. The latter can occur if an object of a __value class object is embedded in an object of a __gc class.


To achieve safety, certain restrictions apply to __gc pointers.

  • A __gc pointer shall not be converted to a __nogc pointer of any type unless the __gc pointer is a pinning pointer (Section 7.7).
© 2015 Microsoft