c++ - 如何在 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
工作的,这可能就是我无法实现它的原因。
解决方案
您的实现create()
应该类似于
static std::unique_ptr<Reader> create(const QString& file) {
if (file == "<string for Reader1>")
return std::make_unique<Reader1>(...);
...
}
推荐阅读
- android - 如何通过调用使用 XSSFWorkbook 的 servlet 在 Android webView 上下载 excel 文件
- python - 文本文件转 JSON
- python - 具有相同时区信息的两个 python 日期时间对象的打印方式不同
- java - 替换 Camera.addCallbackBuffer()
- javascript - 赛普拉斯和谷歌登录
- rest - POST API 请求正文被 Istio 拒绝
- python - 用更多/更少的数据覆盖 Excel 工作表
- c# - 使用 winappdriver 最大化桌面窗口无法正常工作
- python - 如何在登录 EC2 实例时永久激活所需的环境
- apache-flink - Flink SQL Tumble 聚合结果未写入本地文件系统