【问题标题】:Weird behaviour with STL containers (construction/destruction and scope)STL 容器的奇怪行为(构造/销毁和范围)
【发布时间】:2013-02-11 15:21:51
【问题描述】:

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

#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%02d\n", myid);
    }
    ~Entry() { printf("~Entry%02d\n", 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] = %s\n", 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 应该只有一个元素,这不是问题所在。最让我困惑的是,一个条目怎​​么会被破坏多次?

【问题讨论】:

  • 复制构造函数被调用。您拥有的元素比您想象的要多得多。
  • @mkaes 在使用-O2 之类的优化时,它们会被优化掉吗?
  • 小蝶和苹果杰克+1

标签: c++ stl scope


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢,请随意想象我在微笑 :)
猜你喜欢
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
  • 2022-11-29
  • 2020-03-24
  • 1970-01-01
  • 2017-12-07
相关资源
最近更新 更多