1

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.

Oliver S.
  • 57
  • 4
  • 1
    TL;DR of the dupe: const reference class members do not extend the life of temporaries, so you are are trying to call a function on an object that no longer exists. – NathanOliver Jul 26 '22 at 14:05
  • But why is it working for a non virtual function then? – Oliver S. Jul 26 '22 at 14:07
  • 1
    It happens to "work" in that case because there is nothing needed from the object to actually call the function (no vtable needs to be used). You still have undefined behavior and code isn't actually correct. This is a nasty part of undefined behavior. The code can appear to do exactly what you want it to, but there is no guarantee it will stay that way. – NathanOliver Jul 26 '22 at 14:10

0 Answers0