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 typestd::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?
If you can only change C, you could do something like:
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
sayssaid (deleted answer), if you can change B, it would be better to take thatauto_ptrargument by value; and if you can change compiler, it would be better to useunique_ptrand move semantics instead.