gpt4 book ai didi

D struct 内存处理 - 从成员函数返回 `this`

转载 作者:行者123 更新时间:2023-12-04 06:00:30 25 4
gpt4 key购买 nike

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

保存1:
S s = S(1);
S t = S(1);

t = s.save1();

// Gives:
// new 0
// new 1
// copy 2
// del 1
// del 2
// del 0

保存2:
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() 变体从不“删除” i == 2 的结构体。是否存在内存泄漏?如果我使用 auto,我将无法正确管理结构中的资源作为返回类型。

此外,如果 save() 只需返回 this没有临时,我得到:
S save()
{
return this;
}

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

这些是bug吗?如果我不能定义默认构造函数,我应该如何进行适当的内存管理?这个设计决定背后的原因是什么?

我想将它用于前向范围,所以我不能使用 class .

最佳答案

对我来说看起来像一个错误。显然 save1 之间的唯一区别和 save2是后者使用auto return 而不是显式返回类型。除了在此处不适用的少数极端情况外,这应该对 postblit 和 d'tor 调用没有影响。

关于D struct 内存处理 - 从成员函数返回 `this`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8962935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com