Allocating structs with new?

Jonathan M Davis jmdavisprog at gmail.com
Fri Jul 9 22:06:39 PDT 2010


I thought that classes always went on the heap and that structs always went on 
the stack - so allocating structs with new wouldn't work. Also, I thought that 
delete was deprecated if not outright removed from D. And yet, we have a new bug 
that Andrei reported about destructors for structs not working correctly when 
they're allocated with new (and delete is being used to destroy it in the code 
in the report).

http://d.puremagic.com/issues/show_bug.cgi?id=4442

Code from bug report:

struct S1{ ~this() { writeln("dtor"); } }
void main() {
    auto a = S1();
    auto b = new S1();
    delete b;
    auto c  = new S1();
    c = null;
    GC.collect();
}

Am I missing something here? TDPL was quite clear that classes were reference 
types and structs were value types, and here we appear to have a struct used as 
a reference type. Is this some sort of feature from outside of SafeD, or is it a 
feature that was supposed to be removed but hasn't yet, or what? I know that 
TDPL doesn't cover everything and that what dmd does doesn't always match it 
yet, but from what I understood from reading TDPL, the code above shouldn't 
compile at all since it's using a struct like a class and is using the supposedy 
defunct delete operator.

- Jonathan M Davis


More information about the Digitalmars-d mailing list