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:D構造体のメモリ処理 - メンバ関数からのリターン `this`
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()バリアントは '削除しない' ん構造体はi == 2です。メモリが漏れていますか?戻り値の型としてauto
を使用すると、構造体のリソースを適切に管理できません。また
、単に私が得る、一時的なしthis
を返す()保存した場合:
S save()
{
return this;
}
// new 0
// new 1
// copy 2
// del 1
// del 2
// del 2
は、これらのバグはありますか?デフォルトのコンストラクタを定義できない場合は、どのように適切なメモリ管理を行うのですか?この意思決定の背後にある理由は何ですか?
私は前方範囲に使用したいので、私はclass
を使用できません。
私は最新のリリースを使用して、残りのNRVOの問題を提起し。 –