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

How copying a unique_ptr of one type to another works

本文关键字:类型 unique 复制 另一种 ptr 一种      更新时间:2023-10-16

参照以下代码

#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;
}

哪个构造函数被unique_ptr调用?我看了看cppreference.com和我找到的构造函数(c++17之前)是(为了完成)

constexpr unique_ptr();
constexpr unique_ptr( nullptr_t );
explicit unique_ptr( pointer p );
unique_ptr( pointer p, /* see below */ d1 );
unique_ptr( pointer p, /* see below */ d2 );
unique_ptr( unique_ptr&& u );
template< class U, class E >
unique_ptr( unique_ptr<U, E>&& u );

它们似乎都不接受其他类型的指针。我错过了什么?调用哪个构造函数?

谢谢!

第六,模板构造函数。

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

要求" unique_ptr<U, E>::pointer可隐式转换为pointer "。换句话说,U*需要隐式转换为unique_ptr存储的指针类型。在您的情况下,它是,因为Derived*隐式地转换为Base*