【发布时间】:2021-12-08 18:42:10
【问题描述】:
我想在声明后初始化类内的唯一指针,我尝试了几种方法但无法解决错误..
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*/
}
};
【问题讨论】:
-
您到底遇到了什么错误? #3应该工作。另外,你试过
runtime.reset(createIRuntime())了吗?但是,由于这是在构造函数中,您应该使用成员初始化列表:Test() : runtime(createIRuntime()) {} -
我也尝试了重置,但它也给出了同样的错误,我可以在构造函数中使用成员初始化语法,但我也想知道在类成员方法中我应该怎么做?并且错误与指针的成员函数有关。由于指针未初始化,因此没有成员....
-
术语挑剔:那些是分配,而不是初始化。这种区别在 C++ 中非常重要。
标签: c++ c++11 pointers unique-ptr