Are stack+heap classes possible in D?

Shachar Shemesh via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 19 12:10:10 PDT 2015


On 14/06/15 04:31, Adam D. Ruppe wrote:
> On Sunday, 14 June 2015 at 00:52:20 UTC, FujiBar wrote:
>> I have read that in D structs are always allocated on the stack while
>> classes are always allocated on the heap.
>
> That's not true; it is a really common misconception.
>
> Putting a struct on the heap is trivial and built into the language: `S*
> s = new S();`
>
Well....

Yeah. You would get a reference to a struct. The struct will be on the 
heap. In that narrow sense, you are right that it is possible.

However, this does not behave like a normal struct. In particular, when 
will the destructor be called? (answer: never, not even before the 
memory is collected).

So, no, I think D experts should avoid telling newbies it is okay to 
just "new struct foo".[1]

Shachar

1 - The counter argument is, of course, that struct destructors should 
not be counted upon to do anything useful anyways, as they are far from 
guaranteed to run even in situations where one would expect them to. 
This just relates to another area where D skirts truth in advertising 
when people say that D supports RAII.


More information about the Digitalmars-d-learn mailing list