c++ - 在类中初始化 unique_ptr
问题描述
我想在声明后初始化类内的唯一指针,我尝试了几种方法但无法解决错误..
template <typename T>
struct Destroy
{
void operator()(T *t) const
{
t->destroy();
}
};
class Test
{
std::unique_ptr<IRuntime, Destroy<IRuntime>> runtime;
public:
Test()
{
/*
the function createIRuntime() return type is *IRuntime.
I tried using following but all the ways I got error:
1. runtime = std::make_unique<IRuntime, Destroy<IRuntime>> (createIRuntime());
2. runtime = createIRuntime();
3. runtime = std::unique_ptr<IRuntime, Destroy<IRuntime>> (createIRuntime());
Works fine if I do follow.
std::unique_ptr<IRuntime, Destroy<IRuntime>> runtime(createIRuntime());
*/
/* how to initialize the unique pointer here*/
}
};
解决方案
runtime = std::make_unique<IRuntime, Destroy<IRuntime>> (createIRuntime());
大概IRuntime
是一个抽象类,不能直接构造。
但即使可以按原样构造,也只有第一个模板参数指定要创建的类型。第二个和后续的模板参数指定被调用的构造函数的参数类型。
因此,该语句试图调用一个将对象作为参数的IRuntime
构造函数,并将原始指针传递给该参数。不存在这样的构造函数,因此无法编译。Destroy<IRuntime>
IRuntime*
runtime = createIRuntime();
std::unique_ptr
没有一个operator=
接受原始指针的,只有一个std::unique_ptr
. std::unique_ptr
有一个接受原始指针的构造函数,但该构造函数被标记为explicit
. 所以这也无法编译。
runtime = std::unique_ptr<IRuntime, Destroy<IRuntime>> (createIRuntime());
这是正确的,并且工作得很好:
另一个有效的说法是:
runtime.reset(createIRuntime());
此外,由于您显示的代码位于另一个构造函数中,因此您可以(并且应该)使用该构造函数的成员初始化列表:
Test() : runtime(createIRuntime())
{
}
推荐阅读
- android - 无法从 BottomSheetDialog 启动Activity
- java - Netty - 客户端读写操作
- angular - 将数据从组件发送到控制器
- angular - 在 Angular 5 TypeScript 中触发 keyup 事件
- java - 在 Java 中设置 CLASSPATH 的目的是什么?
- javascript - 使用innerHtml从javascript在ul中添加ul
- java - 当嵌入 Spring Boot 时,支持我的 SQL 的 Apache Ignite 无法以客户端模式启动 - 显示配置不匹配
- linux - 在同一行的两个位置使用 sed 或 awk 从多行中删除模式
- python - pandas:当值是可变长度的集合或列表时,从字典创建一个长/整齐的 DataFrame
- php - 在php中检测呼叫并显示来自星号的弹出窗口