Create class on stack

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Aug 5 19:10:31 PDT 2017


On Sunday, 6 August 2017 at 01:18:50 UTC, Johnson Jones wrote:
> On Saturday, 5 August 2017 at 23:09:09 UTC, Moritz Maxeiner 
> wrote:
>> On Saturday, 5 August 2017 at 17:08:32 UTC, Johnson Jones 
>> wrote:
>>> using gtk, it has a type called value. One has to use it to 
>>> get the value of stuff but it is a class. Once it is used, 
>>> one doesn't need it.
>>>
>>> Ideally I'd like to treat it as a struct since I'm using it 
>>> in a delegate I would like to minimize unnecessary 
>>> allocations. Is there any way to get D to allocate a class on 
>>> the stack like a local struct?
>>
>> The easy way is through std.typecons.scoped [1].
>> Here be dragons, though, because classes are reference types.
>>
>> [1] https://dlang.org/phobos/std_typecons.html#.scoped
>
> Thanks, I didn't think it created on the stack but it makes 
> sense to do so.

See the source [1] as to why: typeof(scoped!T) is a 
(non-copyable) struct that holds the memory for the T object 
inside it.

> The only issue is that it escaping the reference?

Yes, don't escape references, that's the reason for my comment:
>> Here be dragons, though, because classes are reference types.

[1] 
https://github.com/dlang/phobos/blob/v2.075.0/std/typecons.d#L6613


More information about the Digitalmars-d-learn mailing list