スタック オブジェクトは、コンパイラによって自動的に処理されます。
スコープを離れると削除されます。
{
obj a;
} // a is destroyed here
「newed」オブジェクトで同じことを行うと、メモリ リークが発生します。
{
obj* b = new obj;
}
b は破棄されないため、b が所有するメモリを再利用する機能を失いました。さらに悪いことに、オブジェクトはそれ自体をクリーンアップできません。
C では、以下が一般的です。
{
FILE* pF = fopen( ... );
// ... do sth with pF
fclose( pF );
}
C++ では、次のように記述します。
{
std::fstream f( ... );
// do sth with f
} // here f gets auto magically destroyed and the destructor frees the file
C サンプルで fclose を呼び出すのを忘れた場合、ファイルは閉じられず、他のプログラムで使用されない可能性があります。(例: 削除できません)。
別の例では、オブジェクト文字列を示します。このオブジェクト文字列は、構築、代入が可能で、スコープを出ると破棄されます。
{
string v( "bob" );
string k;
v = k
// v now contains "bob"
} // v + k are destroyed here, and any memory used by v + k is freed