[英]Passing unique_ptr<Derived>& to a function accepting unique_ptr<Base>&
I need to pass a unique pointer to a derived class by reference to a function which accepts a reference to a unique pointer to the base class, like here: 我需要通过引用一个函数来传递指向派生类的唯一指针,该函数接受对指向基类的唯一指针的引用,例如:
#include <memory>
using namespace std;
class Base {};
class Derived : public Base {};
void foo(std::unique_ptr<Base>& d){}
int main()
{
unique_ptr<Derived> b = make_unique<Derived>();
foo(b);
}
Why doesn't this code work? 为什么此代码不起作用? I checked out other posts like this one , and the answer seems to be "because C++ wants the types to match exactly", but why is that?
我检查了其他类似这样的帖子,答案似乎是“因为C ++希望类型完全匹配”,但是为什么呢? What dangerous situation am I potentially creating?
我可能造成什么危险情况?
If I instead do this, it compiles: 如果我改为这样做,它将编译:
void foo(unique_ptr<Base>&& d){} foo(move(b));
Is this a reasonable approach? 这是合理的方法吗?
What dangerous situation am I potentially creating?
我可能造成什么危险情况?
Imagine the following implementation for foo: 想象一下foo的以下实现:
void foo(std::unique_ptr<Base>& d){
d.reset(new Base);
}
You now have a std::unique_ptr<Derived>
pointing to an object which is not of type Derived
, and the compiler couldn't give you any kind of warning about it. 现在,您有一个
std::unique_ptr<Derived>
指向一个非Derived
类型的对象,并且编译器无法向您发出任何警告。
The correct solution to your problem, as explained in the comments, is to take a std::unique_ptr<Base>
by value, and move it at the call site. 如注释中所述,对您的问题的正确解决方案是按值获取
std::unique_ptr<Base>
,并将其移至调用站点。
void foo(std::unique_ptr<Base> d) {
// move d to your list
}
int main() {
unique_ptr<Derived> b = make_unique<Derived>();
foo(std::move(b));
}
A simple static_cast from Derived to Base, with an appropriate release call (to transfer the ownership of the resource to the newly created pointer) should work fine. 从派生到基础的简单static_cast,并进行适当的释放调用(将资源的所有权转移到新创建的指针)应该可以正常工作。
int main()
{
unique_ptr<Derived> b = make_unique<Derived>();
std::unique_ptr<Base> basePointer(static_cast<Base*>(b.release()));
foo(basePointer);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.