首页 > 解决方案 > 在类中初始化 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*/
    }
};

标签: c++c++11pointersunique-ptr

解决方案


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())
{
}

在线演示


推荐阅读