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;
}
}
SAVE1:
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:
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
正如你所看到的,save2()变体永远不会'deletes'具有i == 2的结构 . 是否内存泄漏?如果我使用 auto
作为返回类型,我无法正确管理结构中的资源 .
另外,如果save()只返回没有临时的 this
,我得到:
S save()
{
return this;
}
// new 0
// new 1
// copy 2
// del 1
// del 2
// del 2
这些错误?如果我不能定义默认构造函数,我该如何进行适当的内存管理?这个设计决定背后的原因是什么?
我想将它用于前进范围,所以我不能使用 class
.
2 回答
对我来说看起来像个错误 . 显然,
save1
和save2
之间的唯一区别是后者使用auto
返回而不是显式返回类型 . 除了几个不喜欢电话的角落情况 .无法使用git dmd重现错误的代码部分:
我提交了剩余的NRVO问题http://d.puremagic.com/issues/show_bug.cgi?id=7353