D结构内存处理-从成员函数返回'this'

D结构内存处理-从成员函数返回'this',d,D,保存1: uint ci = 0; struct S { uint i; this(int x) { i = ci; ci++; writeln("new: ", i); } this(this) { i = ci; ci++; writeln("copy ", i); } ~this() { writ

保存1:

uint ci = 0;

struct S
{
    uint i;

    this(int x)
    {
        i = ci;
        ci++;

        writeln("new: ", i);
    }

    this(this)
    {
        i = ci;
        ci++;

        writeln("copy ", i);
    }

    ~this()
    {
        writeln("del ", i);
    }

    S save1() // produces 2 copies in total
    {
        S s = this;
        return s;
    }

    auto save2() // produces 3 copies in total
    {
        S s = this;
        return s;
    }
}
保存2:

S s = S(1);
S t = S(1);

t = s.save1();

// Gives:
// new 0
// new 1
// copy 2
// del 1
// del 2
// del 0
如您所见,save2()变量从不“删除”i==2的结构。是内存泄漏吗?如果使用
auto
作为返回类型,则无法正确管理结构中的资源

另外,如果save()只返回
this
,而不返回临时值,则得到:

S s = S(1);
S t = S(1);

t = s.save2();

// Gives:
// new 0
// new 1
// copy 2
// copy 3
// del 3
// del 1
// del 3
// del 0
这些是虫子吗?如果无法定义默认构造函数,我应该如何进行适当的内存管理?这一设计决策背后的原因是什么


我想将其用于前向范围,因此无法使用

在我看来,这是一个bug。显然,
save1
save2
之间的唯一区别在于后者使用
auto
返回而不是显式返回类型。除了一些不适用于此处的特殊情况外,这对postblit和d'tor调用没有影响。

无法使用git dmd复制错误的代码部分:

S save()
{
    return this;
}

// new 0
// new 1
// copy 2
// del 1
// del 2
// del 2

我提交了剩余的NRVO问题,因为我使用了最新版本,所以可能当时已经(部分)修复了。
new: 0
new: 1
copy 2
del 1
del 2
del 0
-
new: 0
new: 1
copy 2
copy 3
del 2
del 1
del 3
del 0
-
new: 0
new: 1
copy 2
del 1
del 2
del 0