I don’t know why the destruction of an object in vector is called at the following point of time.
class Something
{
public:
Something() {}
~Something() { cout << "destruction called" << endl; }
};
int main()
{
std::vector<Something> vec;
Something sth1 = Something();
Something sth2 = Something();
vec.push_back(sth1);
vec.push_back(sth2);
vec.clear();
}
After I push sth2, destruction for sth1 is called. Why? Shouldn’t sth1 be kept in vec[0]?
Because the
vectorhas to resize its capacity to be able to store two elements instead of one. It allocates a new buffer, it copies the old buffer to the new one, removes the old buffer, and then adds the new object.