Search code examples
c++copyshared-ptr

How to make a copy of an object containing a list of shared pointers?


I would like to make a copy of an object from the following class:

class EventPacket
{

public:
    std::list<std::shared_ptr <Event> >::iterator it;
    std::list<std::shared_ptr <Event> > EventList;
    EventPacket();
    ~EventPacket();

    EventPacket* clone();

    void add(std::shared_ptr<Event> event);
    std::shared_ptr<Event> pop();

    std::list<std::shared_ptr <Event> >::iterator begin(void);
    std::list<std::shared_ptr <Event> >::iterator end(void);
};

Therefore I've implemented the following function:

EventPacket* EventPacket::clone() {
EventPacket *copy = new EventPacket();
*copy = *this;
return copy;

}

It compiles and it seems to run but I'm not sure whether the shared pointers were copied properly such that they remain shared pointers in the copied object. Say, if I copy an object Eventpacket* ep (assuming its Eventlist contains a number of Event objects) and delete the copy afterwards

EventPacket *copy = ep->clone();
delete copy;

will the list of events be automatically released as one would expect it from a list of shared pointers?


Solution

  • but I'm not sure whether the shared pointers were copied properly such that they remain shared pointers in the copied object

    They were.

    Copying a shared_ptr increases it reference count by one, so in your example deleting copy will not release the events yet, but once ep also gets deleted they will.

    Keep in mind that a cloned EventPacket shares the Event objects with the original, this may or may not be desired.