我想在宣告后初始化類內的唯一指標,我嘗試了幾種方法但無法解決錯誤..
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*/
}
};
uj5u.com熱心網友回復:
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())
{
}
在線演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/333420.html
上一篇:在CRTP模板中禁用復制分配
下一篇:使用解構式完成任務
