Idomatic way to guarantee to run destructor?

Steven Schveighoffer schveiguy at gmail.com
Mon May 4 11:50:49 UTC 2020


On 5/4/20 5:47 AM, Olivier Pisano wrote:
> On Monday, 4 May 2020 at 09:20:06 UTC, Ali Çehreli wrote:
>> On 4/30/20 10:04 AM, Ben Jones wrote:> On Thursday, 30 April 2020 at 
>> 16:55:36 UTC, Robert M. Münch wrote:
>>
>> > I think you want to use scope rather than auto which will put
>> the class
>> > on the stack and call its destructor:
>> > https://dlang.org/spec/attribute.html#scope
>>
>> That is correct about calling the destructor but the object would 
>> still be allocated with 'new', hence be on the heap. There is also 
>> library feature 'scoped', which places the object on the stack:
>>
>>   https://dlang.org/phobos/std_typecons.html#scoped
>>
> 
> https://godbolt.org/z/SEVsp5
> 
> My ASM skills are pretty limited, but it seems to me that the call to 
> _d_allocclass is omitted when using scope. At least with LDC and GDC.
> 
> Am I missing something ?

I'm not sure if Ali is referring to this, but the usage of scope to 
allocate on the stack was at one time disfavored by the maintainers. 
This is why std.typecons.scoped was added (to hopefully remove that 
feature).

Though, if dip1000 ever becomes the default, allocating on the stack 
could be a valid optimization.

-Steve


More information about the Digitalmars-d-learn mailing list