本文介绍了将派生类的unique_ptr用作将unique_ptr用作基类的函数的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在尝试使用 unique_ptr 来在将 unique_ptr 用作基础的函数中派生类类。像这样的东西:

I'm trying to use a unique_ptr to derived class in a function that takes a unique_ptr to a base class. Something like:

class Base {};

class Derived : public Base {};

void f(unique_ptr<Base> const &base) {}

…

unique_ptr<Derived> derived = unique_ptr<Derived>(new Derived);
f(derived);

如果我理解正确,此代码应该可以工作,但是会导致以下编译错误:

If I understand this answer correctly, this code should work, but it causes the following compile errors:

IntelliSense:从 std :: unique_ptr<派生,std :: default_delete<派生>没有合适的用户定义转换到 const std :: unique_ptr< Base,std :: default_delete< Base>存在

IntelliSense: no suitable user-defined conversion from "std::unique_ptr<Derived, std::default_delete<Derived>>" to "const std::unique_ptr<Base, std::default_delete<Base>>" exists

如果我将 f 更改为 unique_ptr< Derived> const&衍生,它工作正常,但是那不是我想要的。

If I change f to take unique_ptr<Derived> const &derived, it works fine, but that's not what I want.

我做错了吗?我该怎么办才能解决此问题?

Am I doing something wrong? What can I do to work around this?

我正在使用Visual Studio 2012。

I'm using Visual Studio 2012.

推荐答案

您有三个选择:


  1. 放弃所有权。函数调用后,这将使您的局部变量无法访问动态对象。该对象已转移到被调用方:

  1. Give up ownership. This will leave your local variable without access to the dynamic object after the function call; the object has been transferred to the callee:

f(std::move(derived));


  • 更改 f 的签名:

    void f(std::unique_ptr<Derived> const &);
    


  • 更改变量类型:

  • Change the type of your variable:

    std::unique_ptr<base> derived = std::unique_ptr<Derived>(new Derived);
    

    或者当然只是:

    std::unique_ptr<base> derived(new Derived);
    

    甚至:

    std::unique_ptr<base> derived = std::make_unique<Derived>();
    


  • 更新:或者,按照评论的建议,不要完全不转让所有权:

  • Update: Or, as recommended in the comments, don't transfer ownership at all:

    void f(Base & b);
    
    f(*derived);
    


  • 这篇关于将派生类的unique_ptr用作将unique_ptr用作基类的函数的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    1403页,肝出来的..

    09-06 08:28