Search code examples
c++inheritanceg++radixrvalue

How do I construct a base class which receives a reference argument?


I can't compile the following code using g++ 4.1.2:

#include <memory>

class A
{
    public:
};

std::auto_ptr<A> GetA()
{
    return std::auto_ptr<A>(new A);
}

class B
{
    B(std::auto_ptr<A>& pA)
    {
    }
};

class C : public B
{
    C() : B(GetA())
    {
    }
};

I get:

invalid cast of an rvalue expression of type std::auto_ptr<A> to type std::auto_ptr<A>&

The problem is I can't define a variable and pass its reference because I am inside a initialization list.

How can I do that when I am only allowed to change class C?


Solution

  • If you can only change C, you could do something like:

    class C: public B
    {
        explicit C(std::auto_ptr<A>& pA) : B(pA) {}
    
    public:
        static C *GetC()
        {
            std::auto_ptr<A> pA = GetA();
            return new C(pA);
        }
    };
    

    The problem is trying to bind a non-const reference to the temporary returned by GetA. If you can assign that to a variable first, you have an lvalue and it works ok.

    As Alex B says said (deleted answer), if you can change B, it would be better to take that auto_ptr argument by value; and if you can change compiler, it would be better to use unique_ptr and move semantics instead.