Transforming a range back to the original type?

Jonathan M Davis jmdavisProg at gmx.com
Fri May 4 10:09:06 PDT 2012


On Friday, May 04, 2012 11:47:31 Steven Schveighoffer wrote:
> Yes, a struct can do reference semantics, but it makes little sense to
> fight the type system and shoehorn it into reference semantics, when
> classes are reference types by default.

A struct makes a lot more sense than a class when you need deterministic 
destruction. IIRC, the last time that it was discussed, it was decided that 
we'd go with structs rather than classes, because it would work better with 
custom allocators, but it was a rather involved discussion, and I don't 
remember all of the details.

With a class though, you would _have_ to wrap it in a struct to be able to 
properly destroy it if it weren't garbage collected, or you'd have to manually 
free it, which would be far less safe and would make how you use the class 
vary widely based on the custom allocator. For instance, if your custom 
allocator used malloc and free, you'd need the container to be reference 
counted in order to clean itself up properly. The closest that you could get 
with classes without wrapping them in a struct would be to have the container 
allocated on the GC heap and have its guts allocated by the custom allocator. 
But if you used a struct, then the struct itself would be on the stack, 
avoiding the heap allocation and giving you the deterministic destruction that 
most allocators will need.

If you're just going to use the GC heap, then classes are going to generally 
be better for reference types, because they naturally have reference 
semantics, but if custom allocators are involved, as far as I can tell, you 
pretty much need structs to get deterministic destruction and thus have the 
allocators work properly.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list