Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

destroying object in vector when new object added

Tags:

c++

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_back(inObject);// pList is member of my class Vector SomeList 
}
like image 240
boom Avatar asked Mar 29 '26 04:03

boom


2 Answers

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.

like image 101
wheaties Avatar answered Apr 01 '26 06:04

wheaties


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?

like image 45
Michael Kristofik Avatar answered Apr 01 '26 04:04

Michael Kristofik