I have a class hierarchy as follows
#include <iostream>
#include <memory>
class A
{
public:
virtual void Print() = 0;
};
class B : public A
{
public:
void Print()
{
std::cout<<"Hello, world\n";
}
};
void Printer(std::unique_ptr<A> aPtr)
{
aPtr->Print();
}
int main()
{
std::unique_ptr<B> bPtr = std::make_unique<B>();
Printer(std::unique_ptr<A>(bPtr.get())); // Causing double deletion
}
Had I not been working with unique_ptrs
, the solution was a no-brainer. The cast from B*
to A*
during function call would have taken place implicitly and the appropriate method would have been called in the Printer
function using dynamic dispatch.
Although, as I'm using unique_ptrs
, the compiler is complaining that an argument of type std::unique_ptr<A>
can not be initialized by an argument of type std::unique_ptr<B>
.
As in the mentioned code, when I try to get the raw pointer from std::unique_ptr<B>
object bPtr
and wrap it in an std::unique_ptr<A>
, I get double deletion problem as the memory occupied by bPtr
's object is freed first time when the Printer()
function returns, and another time when the main()
function returns.
Is there any way around this, so that I get proper casting from std::unique_ptr<B>
to std::unique_ptr<A>
?