首页 > 解决方案 > 如何在 C++ 中使用 std::unique_ptr?

问题描述

我要做的是使用std::unique_ptr能够打开三种不同类型的文件(.rdr, .rrd, .drr),所有这些文件都具有基类Reader. 基类以及三个阅读器类如下:

class Reader
{
protected:
  vector<Read> _reads;
}

class Reader1 : public Reader
{
private:
  int num;
};

class Reader2 : public Reader 
{
private:
  int num;
};

class Reader3 : public Reader
{
private:
  int num;
};

我需要帮助的是实现以下功能:

static std::unique_ptr<Reader> create(const QString& file) {
// code here
}

这是我迄今为止的尝试:

static std::unique_ptr<Reader> create(const QString& file)
{
    return std::unique_ptr<Reader> (create(file)); // gives the error 'all paths through this function will call itself'
}

这就是我调用函数的方式:

if (tmp == "rdr") {
    file = createTempFile();

    auto readerfile = Reader::create(fileName);

我想我不太明白它是如何unique_ptr工作的,这可能就是我无法实现它的原因。

标签: c++classinheritancestatic-methods

解决方案


您的实现create()应该类似于

static std::unique_ptr<Reader> create(const QString& file) {
    if (file == "<string for Reader1>")
       return std::make_unique<Reader1>(...);
    ...
}

推荐阅读