Поделиться через


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.

Remarks

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.

Example

// 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

Requirements

Compiler option: /clr

See Also

Concepts

Language Features for Targeting the CLR