RAIIイディオム(リソース獲得は初期化です)を研究してください!たとえば、RAIIに関するウィキペディアの記事を参照してください。
RAIIは単なる一般的な考え方です。これは、たとえばC++標準ライブラリstd::unique_ptr
またはstd::shared_ptr
テンプレートクラスで使用されます。
RAIIイディオムの非常に簡単な説明:
try..finally
基本的に、これは他のいくつかの言語で見られるブロックのC++バージョンです。RAIIイディオムは間違いなくより柔軟です。
それはこのように動作します:
重要な点は、スコープがどのように終了するかは問題ではないということです。例外がスローされた場合でも、スコープは終了し、ラッパーオブジェクトのデストラクタが呼び出されます。
非常に大雑把な例:
// BEWARE: this is NOT a good implementation at all, but is supposed to
// give you a general idea of how RAII is supposed to work:
template <typename T>
class wrapper_around
{
public:
wrapper_around(T value)
: _value(value)
{ }
T operator *()
{
return _value;
}
virtual ~wrapper_around()
{
delete _value; // <-- NOTE: this is incorrect in this particular case;
// if T is an array type, delete[] ought to be used
}
private:
T _value;
};
// ...
{
wrapper_around<char*> heap( new char[50] );
// ... do something ...
// no matter how the { } scope in which heap is defined is exited,
// if heap has a destructor, it will get called when the scope is left.
// Therefore, delegate the responsibility of managing your allocated
// memory to the `wrapper_around` template class.
// there are already existing implementations that are much better
// than the above, e.g. `std::unique_ptr` and `std::shared_ptr`!
}