Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All

gcnew

gcnew creates an instance of a managed type (reference or value type) on the garbage collected heap. The result of the evaluation of a gcnew expression is a handle (^) to the type being created.

Memory for managed types is allocated by gcnew, and deallocated by the garbage collector. Memory for native C++ types is allocated and deallocated by the new and delete operators.

If gcnew is unable to allocate memory, it throws an OutOfMemoryException.

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

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

Use gcnew to create a boxed value type for use like a reference type.

// example2.cpp : main project file.
// compile with /clr

#include "stdafx.h"
using namespace System;
value class Boxed {
    public:
        int i;
};

int main()
{
    Boxed^ y = gcnew Boxed;
    y->i = 32;
    System::Console::WriteLine(y->i);
    return 0;
}
32

Compiler option: /clr

Community Additions

ADD
Show:
© 2015 Microsoft