如何将一种类型的 unique_ptr 复制到另一种类型
How copying a unique_ptr of one type to another works
参考以下代码
#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 我发现的构造函数(pre 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 );
None 其中似乎接受了其他类型的指针。我错过了什么?调用了哪个构造函数?
谢谢!
编号 6,模板构造器。
template< class U, class E >
unique_ptr( unique_ptr<U, E>&& u );
除其他一些条件外,还要求 "unique_ptr<U, E>::pointer
可隐式转换为 pointer
"。换句话说,U*
需要隐式转换为您的 unique_ptr
存储的指针类型。在你的情况下,它是,因为 Derived*
可以隐式转换为 Base*
.
参考以下代码
#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 我发现的构造函数(pre 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 );
None 其中似乎接受了其他类型的指针。我错过了什么?调用了哪个构造函数?
谢谢!
编号 6,模板构造器。
template< class U, class E >
unique_ptr( unique_ptr<U, E>&& u );
除其他一些条件外,还要求 "unique_ptr<U, E>::pointer
可隐式转换为 pointer
"。换句话说,U*
需要隐式转换为您的 unique_ptr
存储的指针类型。在你的情况下,它是,因为 Derived*
可以隐式转换为 Base*
.