This question is extension of the question I want to understand how the elements are inserted into the STL Container.
Suppose I have A object;, which I want to insert into any of the STL Container, I understand that there is concept of allocators which handles the memory. But I fail to understand that how the actual object is copied into STL memory. So my object is stored on the stack when I call Container.insert how does STL create copy of this object and stored this objects into its memory.
Any equivalent C++ code would be helpful which simulates the same.
The approach is not that complicated. Basically the container will obtain memory from the allocator and then perform copy-construction (with placement-new over that memory). The easier container to see is
vector:Where
ensure_enough_capacity()determines whether the vector has to grow and does it, that is, it will end up calling the allocator ifsize()==capacity()whenpush_backis called.The next level of complexity is a
list, where each node is allocated on its own, and there is some extra information that the library has to manage. In that case the code would look similar to:Where
xandyare the appropriate pointers to initialize the node’snextandlastpointers (usually would be a pointer to the last node forlastand a pointer to a sentry node –invalid beyond the end– fornext), and assuming that this particular constructor will copy-construct thevalueand then fix all referred pointers.Ordered associative containers have the extra level of complexity of managing the balanced tree, but the approach is the same: allocate a block big enough to hold the value and the extra information, and then use placement-new to build the node. The rest are details of the data structure.