unique_ptr<Derived> 到 unique_ptr<Base> 是自动向上转换的吗?
Is unique_ptr<Derived> to unique_ptr<Base> up-casting automatic?
我知道派生的 class unique_ptr
可以出现在多态类型需要基础 class unique_ptr
的地方。例如,从函数
返回时
unique_ptr<Base> someFunction()
{
return make_unique<Derived>(new Derived());
}
或作为参数传递给函数。
// Function taking unique pointer
void someOtherFunction(unique_ptr<Base>&& ptr)
// Code calling this function
someOtherFunction(std::move(ptrToDerived));
我的问题是:这种向上转型总是自动的吗?或者我们是否需要使用 dynamic_cast
?
明确执行它
(草案)标准说:
// 20.8.1.2.1, constructors
...
template <class U, class E>
unique_ptr(unique_ptr<U, E>&& u) noexcept;
template <class U>
unique_ptr(auto_ptr<U>&& u) noexcept;
这些是来自 any unique_ptr 的构造函数。该标准通过如下条款进一步限制了它们的使用:
24 Remarks: This constructor shall not participate in overload resolution unless U*
is implicitly convertible to T*
and D
is the same type as default_delete<T>
这句话的效果是 unique_ptr<T>
可以从 unique_ptr<U>
构造,恰好 U*
可以转换为 T*
(并且满足所有删除器要求)。特别是,当 T
是 U
.
的明确 public 基数 class 时
由于构造函数不是 explicit
,它充当从 unique_ptr<U>
到 unique_ptr<T>
的隐式转换器。
我知道派生的 class unique_ptr
可以出现在多态类型需要基础 class unique_ptr
的地方。例如,从函数
unique_ptr<Base> someFunction()
{
return make_unique<Derived>(new Derived());
}
或作为参数传递给函数。
// Function taking unique pointer
void someOtherFunction(unique_ptr<Base>&& ptr)
// Code calling this function
someOtherFunction(std::move(ptrToDerived));
我的问题是:这种向上转型总是自动的吗?或者我们是否需要使用 dynamic_cast
?
(草案)标准说:
// 20.8.1.2.1, constructors
...
template <class U, class E>
unique_ptr(unique_ptr<U, E>&& u) noexcept;
template <class U>
unique_ptr(auto_ptr<U>&& u) noexcept;
这些是来自 any unique_ptr 的构造函数。该标准通过如下条款进一步限制了它们的使用:
24 Remarks: This constructor shall not participate in overload resolution unless
U*
is implicitly convertible toT*
andD
is the same type asdefault_delete<T>
这句话的效果是 unique_ptr<T>
可以从 unique_ptr<U>
构造,恰好 U*
可以转换为 T*
(并且满足所有删除器要求)。特别是,当 T
是 U
.
由于构造函数不是 explicit
,它充当从 unique_ptr<U>
到 unique_ptr<T>
的隐式转换器。