将unique_ptr <Derived>&传递给接受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>指向的对象不是type 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));
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在声明为返回unique_ptr <Base>的函数中返回unique_ptr <Derived>

如何将“unique_ptr<Base>&”推回“vector<unique_ptr<Derived>>”

将unique_ptr <Derived>转换为unique_ptr <Base>

将std :: unique_ptr <Derived>转换为std :: unique_ptr <Base>

是否自动将unique_ptr <Derived>转换为unique_ptr <Base>?

如何将std :: unique_ptr传递给函数

我如何将 std::make_unique<derived>() 转换为 std::unique_ptr<base>

为什么unique_ptr <Derived>隐式转换为unique_ptr <Base>?

“向下转换” unique_ptr <Base>到unique_ptr <Derived>

传递给函数后如何使用unique_ptr?

如何将unique_ptr参数传递给构造函数或函数?

如何将NULL或nullptr传递给接收unique_ptr参数的函数?

将std :: unique_ptr传递给构造函数以获取所有权

C ++:将诸如unique_ptr :: get()之类的参数传递给函数是否安全?

使用已使用 new X() 创建的变量将 std::unique_ptr 传递给函数

将引用参数传递给采用 unique_ptr 的通用引用的函数

如何将包含 std::unique_ptr 的 std::optional 结构传递给函数?

删除函数unique_ptr

从函数返回unique_ptr

vector<unique_ptr<Base> > 使用 Derived 的初始化列表

当基类具有受保护的析构函数时,创建unique_ptr <Base>

unique_ptr析构函数的优势

std :: unique_ptr constexpr构造函数

std :: unique_ptr构造函数的行为

使用已删除的函数unique_ptr

如何将非静态成员函数作为unique_ptr删除器传递

C ++ unique_ptr <Base>指向派生的ptr

将unique_ptr引用传递给boost :: bind?

将std :: unique_ptr传递给类时出错