我喜欢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;
};
const
的作用和避免全局变量或尝试减少范围的目的相同:减少心理负担。当您知道字段在整个对象生命周期中保持不变时,您无需在调试器中或重构时每次查找它。顺便说一句:系统语言 Rust 在这方面采取了更好的方法:它将所有内容都声明为常量,要能够改变变量,必须明确声明为mut
。有点遗憾的是 C++ 只允许在类中使用mut
,因此您无法通过声明大量的 const 别名来模仿这种行为 :c - Hi-Angel