I have some library code (I cannot not change the source code) that returns a pointer to an object (B). I would like to store this pointer as shared_ptr under a class with this type of constructor:
class A
{
public:
A(boost::shared_ptr<B> val);
...
private:
boost::shared_ptr<B> _val;
...
};
int main()
{
B *b = SomeLib();
A a(b); //??
delete b;
...
}
That is, I would like to make a deep-copy of b and control its life-time under a (even if original b is deleted (delete b), I still have an exact copy under a).
I’m new to this, sorry if it seems trivial…
As you say, you have to copy them not just copy a pointer. So either B already has implemented ‘clone’ method or you have to implement some external
B* copy(B* b)which will create new B with same state.In case B has implemented copy constructor you can implement copy as just
In case B has implemented clone method or similar you can implement copy as
and then your code will look like