I have a class which has a shared_ptr
member. The constructor of this class takes a shared_ptr
object which is assigned to its member. Now the problem is, if I assign this object to another object of the same class, both point to same shared_ptr
. And I do not want to do this. Here is the code which resembles the code I have, but when I do the assignment it crashes at the shared_ptr
swap. Please help me to get this working the way I want.
If you execute line obj2=*obj1, you can see, the new shared_ptr gets created in constructor and then a call to assignment happens where swap will get the temp shared_ptr on rhs and ends up recursively killing the stack.
class A
{
public:
virtual ~A(){};
virtual void Test()
{
}
int i;
int j;
};
class C:public A
{
public:
void Test()
{
}
};
class B
{
public:
B::B(const B& rhs) : m_Command(std::make_shared<A>(*rhs.m_Command))
{
}
B::B(B&& rhs) : m_Command(std::move(rhs.m_Command))
{
}
B& B::operator=(B rhs)
{
std::swap(*this, rhs);
return *this;
}
B()
{
}
B(std::shared_ptr<A> command)
{
m_Command=command;
}
void Test()
{
}
std::shared_ptr<A> m_Command;
};
int _tmain(int argc, _TCHAR* argv[])
{
std::shared_ptr<A> cmd(new C());
B *obj1=new B(cmd);
B obj2;
obj2=*obj1;
cmd->i=10;
cmd->j=20;
return 0;
}