对于指向派生对象的基类型指针,make_unique 的语法是什么?

What is the syntax for make_unique for a pointer of base type to a derived object?

考虑以下基础和派生 类。

class base
{
public:
    int i{9};
    virtual void func()
    {
        cout << "base" << endl;
    }
    virtual ~base()
    {

    }
};

class derived : public base
{
public:
    int i{4};
    void func()
    {
        cout << "derived" << endl;
    }

};

我想为 derived 对象创建 base 类型的 unique_ptr。我知道我能做到

std::unique_ptr<base> ptr{new derived};

但当我这样做时

auto ptr = std::make_unique<base>(derived{});
ptr->func();

这会打印 base,这不是我想要的行为。在这种情况下使用 std::make_unique 的正确方法是什么?另外,为什么auto ptr = std::make_unique<base>(derived{})呢?

当你这样做时

auto ptr = std::make_unique<base>(derived{});

make_unique<base> 将创建一个 unique_ptr<base>,这意味着它只会创建一个 base 对象。由于 derived 是从基派生的,因此将其传递给 base 的复制构造函数是合法的,因此代码可以编译,但是你有一个 base,而不是 derived

你需要的是

std::unique_ptr<base> ptr = std::make_unique<derived>();

获取指向 derived 对象的 base 指针。这不是您想要的语法,但它可以正常工作。

如果你用过

auto ptr = std::make_unique<derived>();

那么 ptr 将是 std::unique_ptr<derived>,而不是 std::unique_ptr<base>