Allocating structs with new?

Jonathan M Davis jmdavisprog at gmail.com
Sat Jul 10 00:45:50 PDT 2010


On Friday 09 July 2010 23:31:18 Robert Jacques wrote:
> 
> A new statement can also allocate value types on the heap and return a
> pointer to them. For example, the type of b and c is S1* and the GC
> doesn't know about C's destructor. Please refer to the D spec on new
> (http://www.digitalmars.com/d/2.0/expression.html#NewExpression) or TDPL
> page 51. Both state that any type can be used with new; no limitations
> with regard to reference or non-reference types are mentioned. Also, on
> page 269 of TDPL there is an example of containing a Node*.

I guess that I missed that, though it doesn't help that I've read the class and 
struct chapters more recently, and they made a big deal about how classes were 
reference type and structs were value types and may no mention whatsoever of 
using structs on the heap - that and I rarely use pointers with primitive types 
even in C++, and I pretty much never use pointers in D. I think that I was 
thinking that you had to use malloc to put primitive types no the heap though. 
It never occurred to me to put a struct on the heap. Obviously, it's not a 
feature that I use often.

I don't mind that it be possible with new, but it is potentially confusing. Oh 
well, at least I'm aware of it now. If I ever want to use new in that manner 
though, I'm obviously going to have to study up on the subject more. I'm quite 
clear about how all that works in languages like C++ or Java, but D is a bit of 
a hybrid when it comes to memory management, and I obviously haven't pick up on 
all of its subtleties yet.

- Jonathan M Davis


More information about the Digitalmars-d mailing list