Allocating structs with new?

Adam Ruppe destructionator at gmail.com
Sat Jul 10 07:04:49 PDT 2010


On 7/10/10, Jonathan M Davis <jmdavisprog at gmail.com> wrote:
> I think that I was
> thinking that you had to use malloc to put primitive types no the heap
> though.

D is very similar to C++ here, with the big exception that classes
*must* use new, whereas new is just an option for everything else.

int* a = new int; // valid C++ and D
struct S {}
S* s = new S; // same as int case, works in C++ and D both


> I don't mind that it be possible with new, but it is potentially confusing.

The thing that might be confusing in the example is the auto keyword
hides the fact that you were working with a pointer (S*) instead of
the object itself (S). Since D doesn't have the -> operator like C++,
working with the S and the S* is the same in most ways, so they look
virtually identical.

But as far as new's functionality, that's the same as C++, returning a
pointer to a heap allocated whatever you want. Oh, there is one big
difference between D and C++ new: in D, it is garbage collected, so
you never have to call delete explicitly.


More information about the Digitalmars-d mailing list