Export (0) Print
Expand All
0 out of 3 rated this helpful - Rate this topic

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:
© 2014 Microsoft. All rights reserved.