看一下这段代码。
class Obj{
public:
int id;
Obj(int id) : id(id){}
};
int main()
{
std::vector<Obj> v;
for(int i=0; i<3; i++) // add some elements
v.push_back(Obj(i));
Obj& ref = v[2]; // grab references (two ways)
Obj* ref_bad = &v[2];
for(int i=3; i<100000; i++) // make the vector re-allocate
v.push_back(Obj(i));
std::cout << ref.id << std::endl; // prints 2
std::cout << (*ref_bad).id << std::endl; // prints 2, but always?
return 0;
}
这个简单的代码在两种情况下都会打印 2
,但我不确定这是否是每个可能执行的行为。
由于 vector 在某一点重新分配(嗯,不一定总是,这取决于操作系统的段管理决策),因此此打印不应该在某一点失败吗?
我在不同点使用 printf
和 %p
打印了指针,并且值不同,但我不完全理解 C++ 真实引用的行为;这样做总是安全的吗? (对可能改变其内存位置的内容进行 C++ 引用)
最佳答案
您的程序有未定义的行为。
在v
上调用 push_back()
时,ref
和 ref_bad
失效。
来自http://en.cppreference.com/w/cpp/container/vector/push_back :
If the new
size()
is greater thancapacity()
then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.
关于c++ - 这个 std::cout 最终会打印垃圾或意外的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43486914/