User-defined reference types are data types a programmer develops that are accessed using
handles,
and where the actual data object is located on the managed heap. All reference types in
C++/CLI are
garbage collected.
C++/CLI provides four kinds of user-defined reference types: arrays, classes, interfaces,
and
delegates. All four of these types share one thing: to create an instance of them required
the gcnew
operator.
new vs. gcnew
The gcnew operator is new to all C++/CLI developers. It appears for the first time with .NET
version 2.0
and replaces the well-known new operator, which was used in all prior versions of C++/CLI
(Managed
Extensions for C++). Its purpose is to create an instance of a reference type object on the
managed
heap and return a handle to this instance. This differs from the new operator, which creates
an
instance of a native class on the CRT heap and returns a pointer to this instance.
■Unsafe Code The new operator is used to create an instance of an object on the CRT heap
and create a pointer
to this object, and thus you lose the benefits of the .NET version 2.0 CLR.
Why a new operator? The gcnew and new operators do different things. When you think of it,
it
sort of makes sense. Why confuse things by using the same operator? Why not improve
readability
of the code and make it obvious which types of object you are creating? Hence, the new
operator
gcnew and the new handle with the caret [^] symbol were created.
浙公网安备 33010602011771号