我喜欢const成员变量的想法,特别是当我将C函数包装到类中时.构造函数获取在整个对象生命周期内保持有效的资源句柄(例如文件描述符),析构函数最终将其关闭.(那是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) …Run Code Online (Sandbox Code Playgroud)