Export (0) Print
Expand All

ref new, gcnew (C++ Component Extensions)

The ref new aggregate keyword allocates an instance of a type that is garbage collected when the object becomes inaccessible, and that returns a handle (^) to the allocated object.

Memory for an instance of a type that is allocated by ref new is deallocated automatically.

A ref new operation throws OutOfMemoryException if it is unable to allocate memory.

For more information about how memory for native C++ types is allocated and deallocated, see the new and delete operators.

Use ref new to allocate memory for Windows Runtime objects whose lifetime you want to administer automatically. The object is automatically deallocated when its reference count goes to zero, which occurs after the last copy of the reference has gone out of scope. For more information, see Ref classes and structs.

Compiler option: /ZW

Memory for a managed type (reference or value type) is allocated by gcnew, and deallocated by using garbage collection.

Compiler option: /clr

Example

The following example uses gcnew to allocate a Message object.

// mcppv2_gcnew_1.cpp
// compile with: /clr
ref struct Message {
   System::String^ sender;
   System::String^ receiver;
   System::String^ data;
};

int main() {
   Message^ h_Message  = gcnew Message;
  //...
}

Example

The following example uses gcnew to create a boxed value type for use like a reference type.

// example2.cpp : main project file.
// compile with /clr
using namespace System;
value class Boxed {
    public:
        int i;
};
int main()
{
    Boxed^ y = gcnew Boxed;
    y->i = 32;
    Console::WriteLine(y->i);
    return 0;
}

Output

32
Show:
© 2014 Microsoft