Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
8 __gc References

8 __gc References

Visual Studio .NET 2003

A __gc reference is similar to a C++ reference, except that the referenced object can be moved during execution by the garbage collector.

Example

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

__gc class G {
public:
   int i;
};

int main() {
   G & g = *(new G);
   g.i = 10;
   System::Console::WriteLine(g.i);
}

Output

10

Characteristics

  • The address of a __gc reference is a __gc pointer.

Example

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

__value struct G { int i; };

int main() {
   G g;
   G & v = g;
   v.i = 4;
   G __gc * p = & g;   // __gc is optional 
   p -> i = 6;
   System::Console::WriteLine(v.i);
}

Output

6

Where convenient, __gc references can be used instead of __gc pointers. Every __gc reference abides by all C++ rules for references. The default rules for the __gc and __nogc keywords on references are the same as for pointers: the reference is __gc whenever the modified type is managed.

Example

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

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

void f( V & w ) {   // __gc reference by default
   w.i = 10;
};

void f( G & h ) {   // __gc reference by default
   h.i = 20;
};

int main() {
   V v;
   G * pG = new G;
   f(v);   //call f by reference
   System::Console::WriteLine(v.i);
   f(*pG);   //call the other f by reference
   System::Console::WriteLine(pG->i);
}

Output

10
20
Show:
© 2015 Microsoft