user367848
user367848

Reputation: 23

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 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.

Upvotes: 2

Views: 1433

Answers (2)

Michael Anderson
Michael Anderson

Reputation: 73470

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

Upvotes: 1

James McNellis
James McNellis

Reputation: 354979

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.

Upvotes: 10

Related Questions