我需要通过引用一个函数来传递指向派生类的唯一指针,该函数接受对指向基类的唯一指针的引用,例如:
#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);
}
为什么此代码不起作用?我检查了其他类似这样的帖子,答案似乎是“因为C ++希望类型完全匹配”,但是为什么呢?我可能造成什么危险情况?
如果我改为这样做,它将编译:
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] 删除。
我来说两句