Consider the following code:
class A
{
public:
virtual uint32_t getNumber() const
{
return 0;
};
};
class B
{
public:
B( const A& a )
: a_( a )
{}
const A& a_;
void test()
{
a_.getNumber(); // error
}
};
B b{ A{} };
int main()
{
b.test();
return 0;
}
Compiling this code with MSVC compiler and executing it will result in an exception thrown when calling a_.getNumber(). Making "getNumber()" non virtual will run the code without exception:
class A
{
public:
uint32_t getNumber() const
{
return 0;
};
};
What is the mechanism behind this not working? How long are const references to RValues are valid? Does each compiler handle this the same way? I have had a compiler where this was working.