c++11 - 移动构造函数和 const 成员变量

标签 c++11 raii move-constructor

我喜欢 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/

相关文章:

c++ - 关于在 CentOS-6.5 上安装 gcc-6.* 的问题

c++ - 5 法则(对于构造函数和析构函数)是否过时了?

c++ - 通过构造函数和析构函数实现 RAII 是否被认为是错误的 'Modern C++'?

c++ - 调用复制 ctor 而不是移动 ctor

C++ 移动构造函数和作用域

c++ - 对于构造函数,我如何在可变参数模板与 std::initializer_list 之间进行选择?

c++ - 如何使用 std::function 作为模板

c++ - 使用带嵌套 vector 的迭代器的意外行为

memory-management - D 动态阵列 - RAII

c++ - 两步复制省略以在构造函数调用中捕获右值作为实例变量