1

Does the copy constructor of any std::container (specifically std::queue) containing object pointers call the member's copy constructors to allow deep copies or does it perform a shallow copy on the pointer values?

Example:

/*******************************************************************************
 * <summary>
 *  Initializes a new instance of the EventHandler class.
 * </summary>
 *
 * <param name="handler">The handler to copy.</param>
*******************************************************************************/
EventHandler::EventHandler(const EventHandler& handler) : _eventQueue(handler._eventQueue) { }

_eventQueue is declared as: std::queue<Event*> _eventQueue; where Event is a Base class with a copy constructor and has multiple derived classes with their own copy constructors.

P.S.: I looove AtomineerUtils and VisualAssistX (especially when combined! :D)

EDIT:

Given the answers below, would this be a proper way to create copy of the original such that the original is unmodified or will the copy be a reverse of the original (simple fix but still an important distinction)?

EventHandler::EventHandler(const EventHandler& handler) {
    for(size_t i = 0; i < handler._eventQueue.size(); ++i) {
        this->_eventQueue.push(new Event(handler._eventQueue._Get_container().at(i)));
    }
}
Casey
  • 10,297
  • 11
  • 59
  • 88
  • Similar: http://stackoverflow.com/questions/5096464/default-assigment-operator-in-c-is-a-shallow-copy. Although that's about copy assignment rather than copy construction, pretty much everything said over there applies to both. – Steve Jessop Jul 27 '11 at 18:55

2 Answers2

5

It performs a deep copy (on the contained object).

So all the contained elements are copied into the new container.

But since your container contains pointers,

std::queue<Event*>   eventQueue;

it is only copying the pointer Event* (as this is the contained object). In this case the object that is pointed at by the container elements are not copied..

Martin York
  • 257,169
  • 86
  • 333
  • 562
0

std::queue is an adaptor (default is deque), therefore it stores a copy of an object, but since you use it like this :

std::queue< Event* >

then the container's value is a pointer type, and only the pointer is copied.

BЈовић
  • 62,405
  • 41
  • 173
  • 273
  • Technically speaking it does call a copy constructor or copy assignment on the pointer itself, but since the pointer is a primitive that is simply a `mov` in Assembly, AKA a bitwise copy. – Paul Stelian Nov 03 '18 at 12:29