Export (0) Print
Expand All

4.1 operator __gc new

Visual Studio .NET 2003

Objects of __gc classes are created using the managed operator __gc new. Memory for the object is allocated on the garbage-collected heap that is managed by the common language runtime.

Characteristics

  • When creating an object of a __gc class, the __gc keyword can be omitted from the new operator. The result is equivalent to using __gc new.

Constraints

  • __nogc new shall not be used to create an object of a __gc class.
  • A call to the managed new operator shall not have placement arguments.
    // __gc_classes8.cpp
    // compile with: /clr
    #using <mscorlib.dll> 
    __gc struct M {
    };
    
    char bytes[256];
    int main() {
       M *m1 = new (&bytes) M();   // C3828
    }
    

The semantics of constructors in the common language runtime differs from C++. Suppose the constructor of a derived class is called, and the base class's constructor calls a virtual function that is overridden in the derived class.

In Managed Extensions and other .NET languages, the derived class's overriding function will be called. This occurs before the constructor for the derived class is called. Any data members of the derived class are zero-initialized by the runtime and will not have the values prescribed by their constructor. The call to the derived class's constructor then may reinitialize data members to other values.

// __gc_classes9.cpp
// compile with: /clr
#using <mscorlib.dll>
using namespace System;

 __gc class base {
public:
   base() { grains = count_grains(2); }
   virtual int count_grains(int i) { return i*i; }
   void update_grains(int i) { grains = i; }
   int show_grains() { return grains; }

protected:
   int grains;
};

__gc class derived: public base {
public:
   derived(int val):value(val) { }
   int count_grains(int i) { return i*i*value; }
private:
   int value;
};

int main() {
   base * b = new base;
   // similar to C++
   Console::WriteLine(b ->show_grains()); 

   // derived's count_grains called by base 
   derived * d = new derived(2); 

   // grains calculated from runtime zero-initalized value
   Console::WriteLine(d ->show_grains());

   // grains calculated from derived constructor's initialized value
   Console::WriteLine(d->count_grains(2));
}

Output

4 
0
8
Show:
© 2014 Microsoft