【发布时间】:2016-12-22 10:12:35
【问题描述】:
以下虚拟程序模仿了我正在排除故障的另一个程序的行为。
#include <iostream>
#include <vector>
class A
{
public:
std::vector<int> data;
void DoTheThing()
{
while (data.size() < 10) {
data.push_back(1);
}
}
};
class B
{
public:
std::vector<A> objs;
B()
{
A one, two, three;
objs.push_back(one);
objs.push_back(two);
objs.push_back(three);
}
void DoTheThing()
{
for (auto obj: objs) {
obj.DoTheThing();
std::cout << "DEBUG length during=" << obj.data.size() << std::endl;
}
}
};
int main()
{
B b;
b.DoTheThing();
for (auto obj : b.objs) {
std::cout << "DEBUG length after=" << obj.data.size() << std::endl;
}
}
我编译并运行为:
$ g++ -Wall --std=c++11 -o test test.cpp
$ ./test
DEBUG length during=10
DEBUG length during=10
DEBUG length during=10
DEBUG length after=0
DEBUG length after=0
DEBUG length after=0
$
由于某种原因,b 的objs 向量中的A 对象的状态在b.DoTheThing() 调用和随后的打印语句之间发生变化。我的问题是发生了什么? A 对象 data 向量是否以某种方式超出范围并被删除,或者可能是整个 A 对象?这似乎是一个范围界定问题——甚至可能是一个微不足道的简单问题——但自从我用 C++ 编程以来,它已经足够长了,我不确定。在其他方法中调用b.DoTheThing() 后,如何使data 向量的内容保持不变?
【问题讨论】: