从结构数组返回时为什么不调用this(this)?

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();
}

D2.058中的上述内容给出:

In this(this)

In ~this():localString

In ~this():defaultString

In ~this():H.m_s

In ~this():H.m_s

上面只生成了一个this(this)(来自getSMem()调用). getSLocal()调用可以只移动结构.但是,为什么getSVec()不会导致this(this)?我注意到这是std.container.Array中保存的引用计数结构的上下文,与this()相比,对此(this)的调用太少了.

最佳答案 在getSVec的情况下,它看起来像一个bug,可能与
this one有关,尽管情况并不完全相同.您应该报告您的具体示例,因为它可能不是完全相同的错误.

但是,如您所说,在getSLocal的情况下,移动了局部变量,因此不会进行复制,也不需要进行postblit调用.这只是getSVec,它是错误的.

点赞