2012-01-22 9 views
2
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を使用できません。

答えて

2

私にはバグのようです。明らかにsave1save2の唯一の違いは、後者が明示的な戻り値の代わりにautoの戻り値を使用することです。ここでは適用されないいくつかのコーナーケースを除いて、これはポストブライトとコールには影響しません。

1

のgit DMDと間違っているコード部分を再現することはできません:

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 

私はので、多分それはすでにだ(一部)を固定し、http://d.puremagic.com/issues/show_bug.cgi?id=7353

+0

私は最新のリリースを使用して、残りのNRVOの問題を提起し。 –

関連する問題