为什么叫破坏?

Cha*_*Don 0 c++

我不知道为什么在下一个时间点调用向量中对象的破坏.

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();
}
Run Code Online (Sandbox Code Playgroud)

在我按下sth2后,调用sth1的破坏.为什么?不应该保留在vec [0]中吗?

GMa*_*ckG 10

因为vector必须调整其容量才能存储两个元素而不是一个元素.它分配一个新缓冲区,它将旧缓冲区复制到新缓冲区,删除旧缓冲区,然后添加新对象.