Search code examples
c++shared-ptrcopy-constructor

How to properly duplicate an object given its shared_ptr


I'm trying to make a duplicate of an object of a custom class Event. I have a shared pointer to the object that I've obtained from its allocation:

std::shared_ptr<Event> e = std::make_shared<Event>();

In order to get a true duplicate of e (not just a copy of the pointer) I've tried:

std::shared_ptr<Event> o = std::make_shared<Event>(*e);

But I'm not sure if this is the correct way as it seems that if I delete e it also deletes o...

Btw, I haven't defined a copy constructor Event::Event(const Event &orig) but in my understanding this is not necessary as the compiler provides a default copy constructor. The event class only contains variables and no further pointers.


Solution

  • std::make_shared is just a simple template function that creates the objects, passing all arguments to the constructor :

    template<class T, class... Args>
    shared_ptr<T> make_shared(Args&&... args)
    {
      return shared_ptr<T>( new T( std::forward<Args>( args )... ) );
    }
    

    In your particular case :

    std::shared_ptr<Event> o = std::make_shared<Event>(*e);
    

    the object is copied.

    If your code is such :

    void foo() {
        // create new object using default constructor
        std::shared_ptr<Event> e = std::make_shared<Event>();
        // create new object using copy constructor constructor
        std::shared_ptr<Event> o = std::make_shared<Event>(*e);
    }
    

    then of course both objects are destroyed, when they go out of scope.