Destroying an object in a vector when adding a new object

When the vector push_back method is called the previous object in the vector, it is destroyed, which may be the reason for this.

template<typename type> void SomeList<type>::AddElement(type &inObject)
{
    pList.push_back(inObject);// pList is member of my class Vector SomeList 
}
+3
source share
4 answers

A vector does not destroy an object. He replaces it.

For instance:

vector< A> myVector; // Do some initialization, etc.
A myNewObject;
myVector[0] = myNewObject; // Replace the object.

This means that the assignment operator (A & A::operator=( const A&)) will be called for myVector[0]. There is no destruction.

Destruction is performed when the vector itself is destroyed or when the memory is redistributed (in this case, the copy constructor is also used to copy objects from the old location to the new location before destroying the old ones).

Then edit. In the case of push_back, destruction should be determined by redistribution.

0

, , "" , , , . , -, . - smart_ptr.

+4

- , . FYI, vector::push_back , . , ?

+1

push_back , . .

, std::vector .

, - . , ( , , ), .
std::vector " ", , , . ( capacity() vs. size() reserve() vs. resize(), .) - , .

, std::deque std::list.

0

Source: https://habr.com/ru/post/1745449/


All Articles