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();