1

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;
}
  • 5
    If you are containing `A` in `B` (composition), why are you also deriving `B` from `A`? If `B` has both an *is-a* and a *has-a* relationship with `A`, your design probably has an issue. And you are violating the [Rule of 3](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)). – Zac Howland Feb 20 '14 at 16:59
  • 2
    Your call to `std::swap` is infinitely recursive and causing StackOverflow(!). See [this](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom), [this](http://stackoverflow.com/questions/12922138/is-the-copy-and-swap-idiom-still-useful-in-c11), [this](http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three), [this](http://stackoverflow.com/questions/4782757/rule-of-three-becomes-rule-of-five-with-c11) and [this](http://stackoverflow.com/questions/8111677/detailed-explanation-on-how-koenig-lookup-works-with-namespaces-and-why-its-a-go) – Ivan Aksamentov - Drop Feb 20 '14 at 17:15
  • Yes that's exactly what's happening. I'm new to C++11, could you please post an example which works or tell me what changes do I need to make to the above example. – user3145865 Feb 20 '14 at 17:25

1 Answers1

1

std::make_shared<A>(*rhs.m_Command) is going to fail if rhs.m_Command is null.

Sneftel
  • 40,271
  • 12
  • 71
  • 104