destroying object in vector when new object added
When push_back method of vector is called the previous object in the vector is getting destroyed what might be the reason for this.
template<typename type> void SomeList<type>::AddElement(type &inObject)
{
pList.push_b开发者_JS百科ack(inObject);// pList is member of my class Vector SomeList
}
It might not be that the object is "destroyed" per se but rather that during reallocation to increase the vector size the object gets copied with the old one being cleaned up. Hence, it is not a good idea to put in something where creation and destruction control program flow. For that I'd suggest another container object or smart_ptr
.
If you post some code, we'll have a much better chance of helping you. FYI, vector::push_back
might cause a reallocation of the internal array so it can grow. Is that what you meant?
The vector doesn't destroy the object. It replaces it.
For example:
vector< A> myVector; // Do some initialization, etc.
A myNewObject;
myVector[0] = myNewObject; // Replace the object.
That means the assignment operator (A& A::operator=( const A&)
) will be called for myVector[0]
. There is no destruction there.
The destruction is done when the vector itself is destructed, or when the memory is reallocated (in this case, the copy constructor is also used, to copy the objects from the old location to the new location, before destroying the old ones).
Later edit In push_back case, the destruction must be determined by a reallocation.
When push_back method of vector is called the previous object in the vector is getting destroyed. What might be the reason for this.
The reason is that std::vector
is specified thus.
When you keep adding elements to the vector, at some point its memory capacity is used up. It then allocates a new memory reserve, copies all the old object to there (plus the one you're adding when it happens), and destroys the old objects.
std::vector
tries to minimize this by "over-allocating", it allocates more memory than required to anticipate further growth. (Look for capacity()
vs. size()
and reserve()
vs. resize()
to learn more about this.) But every reserve might at some point be exceeded, and then it has to re-allocate and copy.
If you don't want this, have a look at std::deque
of std::list
.
精彩评论