我想在聲明後初始化類內的唯一指針,我嘗試了幾種方法但無法解決錯誤..
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())
{
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句