如何将一种类型的unique_ptr复制到另一种类型

时间:2016-06-26 00:34:00

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

参考以下代码

ListView

myObject['myKey'] = myObject['myKey'] || {}; 调用哪个构造函数?我看了cppreference.com,我找到的构造函数(前c ++ 17)是(为了完成)

#include <iostream>
#include <memory>
using std::cout;
using std::endl;
using std::make_unique;

struct Base {};
struct Derived : public Base {};

int main() {

    auto base_uptr = std::unique_ptr<Base>{make_unique<Derived>()};
    return 0;
}

他们似乎都没有接受另一种类型的指针。我错过了什么?调用哪个构造函数?

谢谢!

1 个答案:

答案 0 :(得分:8)

Number 6,模板构造函数。

template< class U, class E >
unique_ptr( unique_ptr<U, E>&& u );

在其他一些条件中,&#34; unique_ptr<U, E>::pointer可以隐式转换为pointer&#34; 。换句话说,U*需要隐式转换为unique_ptr存储的指针类型。在您的情况下,它是,因为Derived*可以隐式转换为Base*