On Mon, July 10, 2006 07:58, bringiton bringiton wrote:
This question is based on curiosity. How does std::vector::pop_back() call the destructor of the item getting removed?
i understood std::vector to be a contigious array of memory, therefore an item's memory does not go out of scope when being popped. ie the item goes out of scope when the entire array goes out of scope.
example code: the reference count is decremented when the item is popped from the vector.
boost::shared_ptr<int> item1(new int(1));
std::vector< boost::shared_ptr<int> > vect1; vect1.push_back(item1);
std::cout << item1.use_count() << std::endl; vect1.pop_back(); std::cout << item1.use_count() << std::endl;
vect1.pop_back() removes an element at the end of the vector. So the element is not there anymore. This is done using the std::allocator class. Even if item's memory remains (I assume a vector implementation can decide whether to keep the last chank for later insert or not), allocator calls destroy and the element is destroyed (its destructor is called, if it is a compound type (the case with shared_ptr)). If destructor of shared_ptr is called its use_count is decreased. With Kind Regards, Ovanes Markarian