c++ - 将 unique_ptr<Derived>& 传递给接受 unique_ptr<Base>& 的函数

标签 c++ c++11 move smart-pointers

我需要通过引用接受对基类的唯一指针的引用的函数来将唯一指针传递给派生类,如下所示:

#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. 为什么这段代码不起作用?我查看了其他帖子,例如 this one ,答案似乎是“因为 C++ 希望类型完全匹配”,但这是为什么呢?我可能会造成什么危险情况?

  2. 如果我这样做,它会编译:

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

    这是一个合理的方法吗?

最佳答案

What dangerous situation am I potentially creating?

想象一下 foo 的以下实现:

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

您现在拥有 std::unique_ptr<Derived>指向不属于 Derived 类型的对象,并且编译器无法向您提供任何类型的警告。

正如评论中所解释的,您的问题的正确解决方案是采用 std::unique_ptr<Base>按值,并将其 move 到调用站点。

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));
}

关于c++ - 将 unique_ptr<Derived>& 传递给接受 unique_ptr<Base>& 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46509006/

相关文章:

c++ - C++ 中 char* 类型的变量

c++ - 为 Qt 项目创建 .deb 包

c++ - 在没有隐式转换的情况下在编译时检测运算符

c++ - 在实时环境中仍然不希望出现异常吗?

java - 如何在java中使现有的多边形 move ?

c++ - 在 logn 中查找排序数组中元素的频率

c++ - 在 vector<string> cocos2d-x 中找到一个词

c++ - 闭包捕获的变量存储在哪里?

Linux : Move files that have more than 100 commas in one line

c++ - 不能 push_back move (NonCopyableWithConstField)到 vector