在類內部初始化 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_ptrstd::unique_ptr有一個接受原始指針的構造函數,但該構造函數被標記為explicit所以這也無法編譯。

runtime = std::unique_ptr<IRuntime, Destroy<IRuntime>> (createIRuntime());

這是正確的,並且工作正常:

在線演示

另一個有效的聲明是:

runtime.reset(createIRuntime());

在線演示

此外,由於您顯示的代碼在另一個構造函數內,您可以(並且應該)使用該構造函數的成員初始化列表:

Test() : runtime(createIRuntime())
{
}

在線演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章