Thread overview
Should __ArrayDtor be called for uninitialised arrays?
November 18

Hi,

The following code calls __ArrayDtor at the end of main. However, since arr is uninitialised, free(p) produces a segmentation fault.

struct S
{
    int *p;

    ~this()
    {
        free(p);
    }
}

void main()
{
    S[3] arr = void;
}

Is this the expected behaviour? One possible fix is to let the programmer handle the destruction of void-initialised arrays themselves.

I am asking because, in _d_arrayctor, the throw introduces call to __ArrayDtor, which destroys the array to. This call is unnecessary, as the _d_arrayctor already destroys the initialised elements of to, while the uninitialised ones need not be destroyed, as I said above.

Thanks,
Teodor

November 18
On Thursday, 18 November 2021 at 12:27:54 UTC, Teodor Dutu wrote:
> Is this the expected behaviour?

Yes, this is specified.

https://dlang.org/spec/struct.html#struct-destructor

It is always called when it goes out of scope. You're supposed to ensure S.init's destructor is a harmless no-op because it is always called. But if you void initialize of course it isn't S.init, it is S.random.

But the spec does give you a way to handle destruction yourself: use a union. See more: http://dpldocs.info/this-week-in-d/Blog.Posted_2021_03_15.html#tip-of-the-week

November 18
On Thursday, 18 November 2021 at 13:32:32 UTC, Adam D Ruppe wrote:
> But the spec does give you a way to handle destruction yourself: use a union. See more: http://dpldocs.info/this-week-in-d/Blog.Posted_2021_03_15.html#tip-of-the-week

This worked. Thanks!