特に C 関数をクラスにラップする場合は、const メンバー変数のアイデアが気に入っています。コンストラクターは、オブジェクトの存続期間全体にわたって有効なリソース ハンドル (ファイル記述子など) を取得し、最終的にデストラクタがそれを閉じます。(それがRAIIの考え方ですよね?)
しかし、C++0x ムーブ コンストラクターを使用すると、問題が発生します。デストラクタは「アンロードされた」オブジェクトでも呼び出されるため、リソース ハンドルのクリーンアップを防ぐ必要があります。メンバー変数は const であるため、値 -1 または INVALID_HANDLE (または同等の値) を割り当てて、何もしないことをデストラクタに示す方法がありません。
オブジェクトの状態が別のオブジェクトに移動した場合、デストラクタが呼び出されないようにする方法はありますか?
例:
class File
{
public:
// Kind of "named constructor" or "static factory method"
static File open(const char *fileName, const char *modes)
{
FILE *handle = fopen(fileName, modes);
return File(handle);
}
private:
FILE * const handle;
public:
File(FILE *handle) : handle(handle)
{
}
~File()
{
fclose(handle);
}
File(File &&other) : handle(other.handle)
{
// The compiler should not call the destructor of the "other"
// object.
}
File(const File &other) = delete;
File &operator =(const File &other) = delete;
};