我喜欢 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) = delete;
};
最佳答案
不,没有办法做到这一点。我建议,如果你真的很喜欢 handle
变量是 const 你应该有一个非常量标志成员变量,指示销毁是否应该做任何事情。
关于c++11 - 移动构造函数和 const 成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6317429/