繁体   English   中英

传递unique_ptr <Derived> &到一个接受unique_ptr的函数 <Base> &

[英]Passing unique_ptr<Derived>& to a function accepting unique_ptr<Base>&

我需要通过引用一个函数来传递指向派生类的唯一指针,该函数接受对指向基类的唯一指针的引用,例如:

#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);
}
  1. 为什么此代码不起作用? 我检查了其他类似这样的帖子,答案似乎是“因为C ++希望类型完全匹配”,但是为什么呢? 我可能造成什么危险情况?

  2. 如果我改为这样做,它将编译:

     void foo(unique_ptr<Base>&& d){} foo(move(b)); 

    这是合理的方法吗?

我可能造成什么危险情况?

想象一下foo的以下实现:

void foo(std::unique_ptr<Base>& d){
    d.reset(new Base);
}

现在,您有一个std::unique_ptr<Derived>指向一个非Derived类型的对象,并且编译器无法向您发出任何警告。

如注释中所述,对您的问题的正确解决方案是按值获取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));
}

从派生到基础的简单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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM