STL容器的怪异行为(构造/破坏和范围)

Weird behaviour with STL containers (construction/destruction and scope)

本文关键字:构造 范围 STL      更新时间:2023-10-16

我不确定STL容器在传递时是否被完全复制。首先,它起了作用(所以没有添加"飘动"元素,这很好)。然后我想跟踪条目的构建和销毁情况。。。。

#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
using namespace std;
int nextid = 0;
class Entry {
public:
    string data;
    int myid;
    Entry(string in) {
        data = in;
        myid = nextid;
        nextid++;
        printf("Entry%02dn", myid);
    }
    ~Entry() { printf("~Entry%02dn", myid); }
};
class Meep {
public:
    vector<Entry> stuff;
};
void think(Meep m) {
    m.stuff.push_back(Entry(string("fluttershy")));
}
int main() {
    Meep a;
    a.stuff.push_back(Entry(string("applejack")));
    think(a);
    vector<Entry>::iterator it;
    int i = 0;
    for (it=a.stuff.begin(); it!=a.stuff.end(); it++) {
        printf("a.stuff[%d] = %sn", i, (*it).data.c_str());
        i++;
    }
    return 0;
}

产生以下意外输出(http://ideone.com/FK2Pbp):

Entry00
~Entry00
Entry01
~Entry00
~Entry01
~Entry00
~Entry01
a.stuff[0] = applejack
~Entry00

a只需要一个元素,这不是问题所在。最让我困惑的是,一个条目怎么能被破坏好几次?

您看到的是临时实例的破坏。

a.stuff.push_back(Entry(string("applejack")));

此行创建一个临时实例,然后将其复制到容器中的另一个新实例。然后临时的就被破坏了。删除条目或销毁容器时,容器中的实例将被销毁。