Why “gcnew T” instead of “new (gc) T”?

On comp.lang.c++.moderated, Peter

  • I also don't see the need for gcnew. Why not use placement new, i.e.:
    T^ h = new (CLI::gc) T(14);
    This would require an extension allows placement new overloads to return
    something other than void* and a standard way to get to the raw storage where to construct
    the object. That extension, however, could be useful for other things as well, i.e.
    a new that returns a smart pointer so you don't have to have a public constructor
    on the smart pointer taking a raw pointer which is dangerous.

There are several reasons why we didn't use a form of placement new.

One reason is that we wanted to leave a door open in case in the future we wanted
to allow placement and class-specific forms of gcnew. Having a parallel gcnew expression
and operator best serves leaving that door open.

Another reason is that existing libraries, including GC libraries, already use placement
forms of new, and so many of the possible placement names are taken.
In particular, new (gc) X; is already taken by the Boehm collector.
Yes, I know you suggested CLI::gc instead of plain gc,
but in practice I'm still concerned that enough people are liable to frequently write using
namespace CLI;
(actually stdcli) to make this problematic.

Still another is one you cite: It's easier to teach that "the type of a new-expression
(and operator new) is a *" today, and that "the type of a gcnew-expression
is a ^".

Finally, a minor reason is that gcnew is slightly less typing than new
or new (cli), and moderately less typing than new

Comments (2)
  1. Edward Diener says:

    I don’t see why you don’t use just ‘new’ rather than ‘gcnew’ ? The type of T will determine whether the obect is allocated in GC collected memory or the C++ heap. The only reason for disambiguating them is if, in the future, CLI will allow allocating a GC object on the C++ heap and/or allocating a non-GC object in the GC collected memory area. But it baffles me why one would ever change the CLI bindings to do that. In the meantime that is not possible, and using a consistent ‘new’ would be much clearer from a C++ programming point of view rather than inventing a different syntax.

  2. Herb Sutter says:

    A good question, with a good answer — I’ll post it as a new blog entry. Thanks,


Comments are closed.

Skip to main content