2

リチャード・ギラムは、彼の「代入演算子の解剖学」の中で、彼の論文の冒頭で次のように述べているため、おそらく間違った発言をしています。

「この質問に対する 1 つの正解は次のようになります。」

TFoo&TFoo::operator=(const TFoo& that)
{
    if (this != &that)
    {
        TBar* bar1 = 0;
        TBar* bar2 = 0;

        try
        {
            bar1 = new TBar(*that.fBar1);
            bar2 = new TBar(*that.fBar2);
        }
        catch (...)
        {
            delete bar1;
            delete bar2;
            throw;
        }

        TSuperFoo::operator=(that);
        delete fBar1;
        fBar1 = bar1;
        delete fBar2;
        fBar2 = bar2;
    }
    return *this;
}

私は作者が間違っているとTSuperFoo::operator=()思いbar1ますbar2

4

1 に答える 1

1

次のようになっている場合、メモリ リークはありません。

Tbar* pBar = NULL;

try
{
    pBar = new Tbar();
}
catch (...)
{
    delete pBar;    // clean memory if it was allocated
    throw;          // error was not handled properly, throw it to caller
}

delete pBar;        // no exception was caught, clean the memory

ただし、最後deleteの .

このような醜いメモリ管理を回避するために、この言語が提供する優れた機能を使用しないコードを書く人がいるのは、ただ悲しいことです。通常、自動ストレージ期間を持つオブジェクトで十分であり、RAIIイディオムに従うか、動的割り当てが必要な状況では、これらのネイキッド ポインターをいくつかのオブジェクトでラップすることをお勧めします... スマート ポインターは大いに役立ちます。

于 2012-12-24T19:48:59.890 に答える