0

I have some code where one class (class B) stores another class (class A) by a const lvalue reference. I've done this so I can avoid copying the instance of class A, if I've understood it correctly then even when initialised with an rvalue the const reference can extend the lifetime to that of the variable (and in this case therefore to that of class B).

Using this concept in code demonstrated by this minimal example seems to work:

class A
{
    A(int ID); 
};

class B
{
    B(const A &a)
    : m_a{a}
    {}

    B(int ID)
    : m_a{A(ID)}
    {}

    private:
        const A &m_a;
};

But, if instead the second constructor for B calls the first, like

B(int ID)
: B(A(ID))
{}

then I get a load of junk out when I try and access information from class A further down the line, so I guess it's no longer pointing to the object I intended it to?

Why do these two examples perform differently? It seems to me that either way the rvalue instance of class A is being passed to a const reference, only that one route is more direct.

Any insight would be appreciated! Of course I can just use the form that is working, but it would be nice to understand what's going on.

EDIT: I actually get a compiler warning telling me m_a will expire outside of the constructor. Adding a std::move around the A(ID) fixed this. It's still worth noting that the code I gave without the standard move works for the duration of the constructor, while the latter starts spitting out garbage even within the constructor still.

0 Answers0