How do I create a duplicate instance of object contained in a shared pointer in c++?
I have an object which has both a copy constructor and assignment operator defined. It is enclosed inside a sha开发者_高级运维red pointer.
I want to make another shared pointer that contains a copy of the original shared pointer (i.e. new shared pointer to a new memory location, which however, has the same data as the original object).
Thanks for any assistance.
You invoke the copy constructor when creating the new object:
std::shared_ptr<C> ptr1(new C()); // invokes the default constructor
std::shared_ptr<C> ptr2(new C(*ptr1)); // invokes the copy constructor
In this case, it's really no different than if you have regular, dumb pointers.
Often I'll be using shared pointers with polymoprphic types. In this case you can't use the method suggested by James McNellis.
class Base
{
...
virtual void doSomething()=0;
};
class Derived : public Base
{
...
void doSomething() { ... }
};
std::shared_ptr<Base> ptr(new Derived);
std::shared_ptr<Base> cpy( new Base( *ptr ) ); // THIS DOES NOT COMPILE!
So what I do instead is to add a clone function into the base class, and implement it in the derived classes.
class Base
{
...
virtual void doSomething()=0;
virtual std::shared_ptr<Base> clone() const =0;
};
class Derived : public Base
{
...
void doSomething() { ... }
std::shared_ptr<Base> clone() const
{
return std::shared_ptr<Base>( new Derived( *this ) );
}
};
std::shared_ptr<Base> ptr(new Derived);
std::shared_ptr<Base> cpy = ptr->clone();
精彩评论