我需要通过引用接受对基类的唯一指针的引用的函数来将唯一指针传递给派生类,如下所示:
#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);
}
为什么这段代码不起作用?我查看了其他帖子,例如 this one ,答案似乎是“因为 C++ 希望类型完全匹配”,但这是为什么呢?我可能会造成什么危险情况?
如果我这样做,它会编译:
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/