当我运行以下代码时,出现以下运行时崩溃:
"调用的纯虚方法 在没有事件异常的情况下终止调用”
我不明白为什么多态在这里不起作用。请有人帮助我。
struct Base
{
virtual void print()=0;
virtual ~Base(){}
};
struct Derived: public Base
{
void print(){cout << "this is Derived\n";}
};
struct Foo
{
Foo(Base&& r): bref{r} {}
void print(){
bref.print();
}
Base& bref;
};
int main()
{
Foo f{Derived()};
f.print(); //it crashes here with above message
}
最佳答案
临时对象 Derived()
的生命周期一直延伸到完整的表达式,即 Foo f{Derived()};
。 f.bref
是之后的悬空引用。 f.print()
调用具有未定义行为的 bref.print()
。
Foo{Derived()}.print();
在技术上定义得很好,但是将左值引用存储到传递给构造函数的右值引用对象中可能没有意义。
关于c++ - 右值引用和多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56873162/