STL容器的怪异行为(构造/破坏和范围)
Weird behaviour with STL containers (construction/destruction and scope)
我不确定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")));
此行创建一个临时实例,然后将其复制到容器中的另一个新实例。然后临时的就被破坏了。删除条目或销毁容器时,容器中的实例将被销毁。
相关文章:
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 构造中错误:未在此范围中声明"data"
- C++11:没有复制构造函数的自定义基于范围的循环
- std::vector 范围构造函数可以调用显式转换吗?
- C++:SFINAE 来区分填充和范围构造函数?
- 如何在C++11中区分填充构造函数和范围构造函数
- 使用范围解析运算符时,在构造函数中调用虚拟方法是否安全?
- 子类化 STL 容器:范围构造函数不起作用
- 基于范围的 std::move 调用意外复制构造函数
- 从较小类型的指针定义的范围构造向量
- 基于容器范围的构造函数效率
- 删除复制构造函数和运算符=类范围访问
- 正确编写基于范围的构造函数
- 在构造函数中 'cout' 未在此范围内声明
- 为什么范围V3产量需要默认构造函数
- 误报警告 PVS 工作室:V821 性能降低。'rhs'变量可以在较低级别的范围内构造
- 当第一个 itr 在最后一个 itr 之后时,std::vector 范围构造函数的官方行为是什么?
- C 11矢量构造函数复制与范围
- 无法从构造函数访问私有变量 - 不在范围(C )中
- 比较迭代器value_type范围构造函数