Are stack+heap classes possible in D?

rsw0x via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 19 12:18:40 PDT 2015


On Friday, 19 June 2015 at 19:10:11 UTC, Shachar Shemesh wrote:
> 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.

the destructor bug has been fixed for a while. for your second 
point, the issue is that D doesn't separate destructors from 
finalizers and it feels like it was designed by someone with 
little knowledge in low level memory management honestly.


More information about the Digitalmars-d-learn mailing list