As I understand temporaries, the following code should work, but it doesn’t.
struct base
{
virtual~base() {}
virtual void virt()const=0;
};
struct derived:public base
{
virtual void virt()const {}
};
const base& foo() {return derived();}
int main()
{
foo().virt();
return 0;
}
The call to virt() gives a “pure virtual function called” error. Why is that, and what should I do?
It seems like you’re expecting the
constreference to extend the lifetime of the temporary. There are certain situations where this doesn’t occur. One of those situations is when returning a temporary:Since calling a member function of the object returned by
foo()will necessitate an lvalue-to-rvalue conversion and the object is invalid (not derived from typebase), you get undefined behaviour: