如何处理不可复制的类?

Ric*_*ord 1 c++

一个例子:

class File {
public:
    File(const char* path);
    File(File& other) = delete;
    File& operator=(File& rhs) = delete;
    ~File();

private:
    char* path;
    FILE* cfile;
};


class Filesystem {
public:
    Filesystem();
    Filesystem(Filesystem& other);
    ~Filesystem();

    File Search(const char* filepath) {
        File file(filepath);
        return file;
    }
private:
};
Run Code Online (Sandbox Code Playgroud)

从 File 类中删除复制构造函数和赋值运算符(因为不应该复制它)后,有什么方法可以从文件系统的搜索函数或其他方法来处理它返回它吗?

Mar*_* Ba 6

可移动类型

您可以通过添加移动构造函数和移动赋值运算符来使类可移动。一些可能有用的概述。)

...
// rough sketch
// Having the path as `char*` seems
//  bad (use std::string instead), 
//  but let's stick with the example as posted)
File(File&& other) 
: path(nullptr)
, cfile(nullptr)
{
  using std::swap;
  // steal the guts of the moved-from object
  swap(path, other.path);
  swap(cfile, other.cfile);
}
Run Code Online (Sandbox Code Playgroud)

移动赋值运算符可能有点棘手,与自赋值检查有关。

/或者/

智能指针

您可以将这些类的实例包装在智能指针中并使用它们:

  • std::shared_ptrstd::unique_ptrETC。
    std::unique_ptr<File> Search(const char* filepath) {
        auto pfile = std::make_unique<File>(filepath);
        ...
        return pfile;
    }
Run Code Online (Sandbox Code Playgroud)

当您使用不支持移动操作的第 3 方类(可能是遗留类)时,这尤其有用。

是的,它们具有堆分配开销,但考虑到打开文件或获取其他阻止复制的昂贵资源的开销,堆分配开销很可能可以忽略不计。

  • 我建议首先使其可移动,如果可移动不适合,然后再回退到指针语义,但其他方面是可靠的建议 (4认同)