-1

動的メモリを割り当てましたが、delete 演算子を使用して関数の最後でメモリをクリアしています。削除前に例外処理があります。この状況でメモリリークを回避するにはどうすればよいですか。

4

2 に答える 2

1

または同様のものを使用std::unique_ptrして、ヒープ割り当てメモリを保持します。次に、例外がスローされたかどうかに関係なく、そのスマート ポインターがスコープ外になると、自動的に割り当てが解除されます。

于 2013-10-06T21:36:59.427 に答える
1

The best way to deal with this is creating a class that contains your allocated memory and deletes it in the constructor.

This is what std::vector does, so when it goes out of scope, the compiler ensures that the memory is deleted (even if it goes out of scope because of a destructor).

For pointers to single values, that's what smart pointers are for. std::auto_ptr (now deprecated) and std::unique_ptr (new in C++ 2011) do that for you.

于 2013-10-06T21:38:43.937 に答える