Managing malloced memory

anon anon at
Mon Oct 11 10:53:15 UTC 2021

On Thursday, 7 October 2021 at 11:55:35 UTC, Steven Schveighoffer 
> The GC is technically not required to free any blocks ever. But 
> in general, it does.
> When it does free a struct, as long as you allocated with 
> `new`, it should call the dtor.

In practice when I played around with it, destructor always got 
called by GC. But: 
says at point 6:
>The garbage collector is not guaranteed to run the destructor 
>for all unreferenced objects.
Is it the same for structs or are these destructors guaranteed to 
be called? Would it be suitable to clean up tempfiles with 
GC-managed structs?

> Just FYI, you should reply to the posts that you quote, or at 
> least copy the "X Y wrote" line so people understand the thread.

Alright. If I want to reply to multiple people, should I post 
twice or quote both in the same post?

> The destructor is called once per copy. This is why disabling 
> copy prevents double freeing.
> There are cases where the compiler avoids calling the 
> destructor because the instance is moved. Such as returning a 
> newly constructed item (typically referred to as an "rvalue"), 
> or passing a newly constructed item into a parameter. The 
> parameter will be destroyed, but the call-site constructed item 
> will not.
> e.g.:
> ```d
> struct S
> {
>    int x;
>    ~this() { writeln("destructor called"); }
> }
> void foo(S s) {
>    // destructor for s called here
> }
> S makeS(int x)
> {
>    return S(x); // no destructor called here.
> }
> void main()
> {
>    foo(S(1)); // no destructor called for this rvalue
>    auto s = makeS(1);
>    // destructor for s called here.
>    foo(makeS(1)); // only one destructor called at the end of 
> foo
> }
> ```
Is there any reference for exactly how these rules apply, or is 
this implementation defined? The 
[specification]( says that destructors are called when objects go out of scope. Your examples seem to suggest that this is untrue in some cases.

More information about the Digitalmars-d-learn mailing list