John
John

Reputation: 405

Why is this(this) not called when returning from array of structs?

import std.stdio;

struct S
{
    string m_str = "defaultString";
    
    this(this)
    {
        writeln("In this(this)");
    }
    
    ~this()
    {
        writeln("In ~this():"~m_str);
    }
    
}

struct Holder
{
    S[] m_arr;
    S m_s;
    
    this(S[] arr)
    {
        m_arr = arr;
        m_s.m_str="H.m_s";
    }
    
    S getSMem()
    {
        return m_s;
    }
    
    S getSVec()
    {
        return m_arr[0];
    }
    
    S getSLocal()
    {
        S local = S("localString");
        return local;
    }
}

void main()
{
    Holder h = Holder(new S[1]);
    
    S s1 =  h.getSMem();
    S s2 =  h.getSVec();
    S s3 =  h.getSLocal();
}

The above in D2.058 gives:

In this(this)

In ~this():localString

In ~this():defaultString

In ~this():H.m_s

In ~this():H.m_s

Only one this(this) is produced in the above (from the getSMem() call). The getSLocal() call can just move the struct. However, why does getSVec() not result in a this(this)? I noticed this is the context of a reference counting struct held in a std.container.Array, and there were too few calls to this(this) compared to ~this().

Upvotes: 4

Views: 253

Answers (1)

Jonathan M Davis
Jonathan M Davis

Reputation: 38287

In the case of getSVec, it looks like a bug, possibly related to this one, though the situation is not exactly the same. You should report your specific example though, since it may not be the exact same bug.

However, as you say, in the case of getSLocal, the local variable is moved, so no copying takes place, and no postblit call is required. It's just getSVec which is buggy.

Upvotes: 2

Related Questions