收录日期:2019/02/17 00:17:02 时间:2010-06-16 02:42:34 标签:c++,shared-ptr,smart-pointers

I have an object which has both a copy constructor and assignment operator defined. It is enclosed inside a shared 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();