【问题标题】:Why is this(this) not called when returning from array of structs?为什么从结构数组返回时不调用 this(this)?
【发布时间】:2012-02-19 20:35:34
【问题描述】:
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 中的上述给出:

在这个(这个)

在~this():localString

在~this():defaultString

在~this():H.m_s

在~this():H.m_s

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

【问题讨论】:

    标签: d


    【解决方案1】:

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

    但是,正如您所说,在 getSLocal 的情况下,局部变量被移动,因此不会发生复制,也不需要 postblit 调用。只是 getSVec 有问题。

    【讨论】:

    猜你喜欢
    • 2016-04-06
    • 2011-05-22
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    相关资源
    最近更新 更多