[英]“Downcasting” unique_ptr<Base> to unique_ptr<Derived> with unique_ptr<Data> in Derived
“Downcasting” unique_ptr< Base > to unique_ptr< Derived > offer an elegent solution to downcasting unique_ptr. “向下转换” unique_ptr< Base > 到 unique_ptr< Derived >为向下转换 unique_ptr 提供了一个优雅的解决方案。 It works in most of time.
它在大部分时间都有效。 But when the Derived contains unique_ptr, something go wrong:
但是当 Derived 包含 unique_ptr 时,就会出错:
template<typename Derived, typename Base, typename Del>
std::unique_ptr<Derived, Del>
static_unique_ptr_cast( std::unique_ptr<Base, Del>&& p )
{
auto d = static_cast<Derived *>(p.release());
return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter()));
}
struct Data
{
int data;
};
struct Base
{
};
struct Derived : public Base
{
Derived()
: data(std::make_unique<Data>())
std::unique_ptr<Data> data;
};
int main()
{
std::unique_ptr<Base> base = std::make_unique<Derived>();
auto data = static_unique_ptr_case<Derived>(std::move(base))->data; // compile error
return 0;
}
Is there a better way to fix the problem?有没有更好的方法来解决这个问题?
Eidt:艾特:
fix the typos and修正错别字和
@Igor Tandetnik give a solution @Igor Tandetnik给出了解决方案
std::unique_ptr<Base> base = std::make_unique<Derived>();
//auto& data = static_unique_ptr_case<Derived>(std::move(base))->data; // compile error
auto derived = static_unique_ptr_case<Derived>(std::move(base));
auto& data = derived->data;
return 0;
The online documentation states this about unique_ptr
:在线文档说明了关于
unique_ptr
这一点:
The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.
该类满足 MoveConstructible 和 MoveAssignable 的要求,但不满足 CopyConstructible 或 CopyAssignable 的要求。
So you cannot copy construct or copy assign a unique_ptr
as you are trying to do in the line:因此,您不能像在该行中尝试那样复制构造或复制分配
unique_ptr
:
auto derived = static_unique_ptr_cast<Derived>(std::move(base))->data; // compile error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.