Create class on stack

Moritz Maxeiner via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 6 08:47:43 PDT 2017


On Sunday, 6 August 2017 at 15:24:55 UTC, Jacob Carlborg wrote:
> On 2017-08-05 19:08, 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?
>
> Prefix the variable declaration with "scope":
>
> scope foo = new Object;

If you use this option, do be aware that this feature has been 
scheduled for future deprecation [1].
It's likely going to continue working for quite a while (years), 
though.

[1] 
https://dlang.org/deprecate.html#scope%20for%20allocating%20classes%20on%20the%20stack


More information about the Digitalmars-d-learn mailing list