#include <iostream>
#include <vector>
#include <cstdlib>
#include <cassert>
struct s_A {
bool bin;
s_A(): bin(0) {}
};
class c_A {
public:
s_A * p_struct;
c_A(): p_struct(NULL) {p_struct = new s_A [16];}
void Reset()
{
delete [] p_struct;
p_struct = new s_A [16];
}
};
int main ()
{
srand(1);
int x = 30;
std::vector <c_A> objects;
objects.assign(x, c_A());
std::vector <c_A> objects_copy;
for(int q=0; q < x; q++)
{
objects_copy.push_back(objects[ rand() % x ]);
objects_copy[q].Reset();
}
for(int q=0; q < 16; q++)
for(int w=0; w < x; w++)
{
// Assertion should not fail, but it does
assert(!objects_copy[w].p_struct[q].bin);
objects_copy[w].p_struct[q].bin = true;
}
}
不知何故,不同复制对象中的指针最终指向相同的内存,断言最终失败。如果在未复制的向量上运行,则不会发生此行为。我认为 c_A.Reset() 应该释放指针(通过 delete[])以指向新数组,但我显然遗漏了一些东西。