移动构造函数和const成员变量 [英] Move constructor and const member variables

查看:111
本文介绍了移动构造函数和const成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢const成员变量的概念,尤其是当我将C函数包装到类中时。构造函数采用资源句柄(例如文件描述符),该句柄在整个对象生命周期内保持有效,而析构函数最后将其关闭。 (那是RAII背后的想法,对吗?)



但是使用C ++ 0x move构造函数时,我遇到了问题。由于析构函数也在卸载对象上调用,因此我需要防止清理资源句柄。由于成员变量是const,因此我无法分配值-1或INVALID_HANDLE(或等效值)来指示析构函数它不应执行任何操作。



如果将一个对象的状态移到另一个对象,是否可以不调用析构函数?



示例:

 类文件
{
public:
//类型为命名构造函数或静态工厂方法
静态文件open(const char * fileName,const char * modes)
{
FILE * handle = fopen(文件名,模式);
返回文件(句柄);
}

private:
文件* const句柄;

public:
File(FILE * handle):handle(handle)
{
}

〜File()
{
fclose(handle);
}

File(File& other):handle(other.handle)
{
//编译器不应调用其他
//对象。
}

File(const File& other)=删除;
File& operator =(const File& other)=删除;
};


解决方案

没有,没有办法。我建议,如果您真的很喜欢 handle 变量为const,则应该有一个非const标志成员变量,该变量指示破坏是否应该做任何事情。 / p>

I like the idea of const member variables especially when I wrap C functions into classes. The constructor takes a resource handle (e.g. a file descriptor) that stays valid during the whole object life time and the destructor finally closes it. (That is the idea behind RAII, right?)

But with the C++0x move constructor i run into a problem. Since the destructor is also called on the "unloaded" object i need to prevent the cleanup of the resource handle. Since the member variable is const i have no way to assign the value -1 or INVALID_HANDLE (or equivalent values) to indicate to the destructor that it should not do anything.

Is there a way that the destructor is not called if the state of an object was moved to another object?

Example:

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;
};

解决方案

No, there is no way to do this. I would suggest that if you're really attached to the handle variable being const you should have a non-const flag member variable that indicates whether or not destruction should do anything.

这篇关于移动构造函数和const成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆