简体   繁体   English

当向量增长时,指向向量元素的 C++ 指针是否会变得无效?

[英]Does C++ pointer to an element of a vector become invalid when vector is growing?

When a vector is growing, then larger memory space is allocated where the whole vector collection is copied.当向量增长时,会分配更大的 memory 空间,复制整个向量集合。

Does any pointer to an element of the vector become invalid after this memory move?在此 memory 移动后,指向向量元素的任何指针是否无效?

Does C++ pointer to an element of a vector become invalid when vector is growing?当向量增长时,指向向量元素的 C++ 指针是否会变得无效?

Yes of course, and that is documented .是的,当然,这是记录在案的 A pointer is a machine address, and when a block of memory is moved (your underlying <vector> implementation is likely to do some memcpy or memmove or their equivalent to move a block) the pointer to it becomes invalid.指针是一个机器地址,当 memory 块被移动时(你的底层<vector>实现可能会做一些memcpymemmove或它们的等价物来移动一个块)指向它的指针变得无效。 Remember that new is nearly a malloc followed by the call of the constructor.请记住, new几乎是malloc ,然后是构造函数的调用。 You could also look at the implementation code of ::operator new if using an open source implementation of C++如果使用 C++ 的开源实现,您还可以查看::operator new的实现代码

And you could also look at the preprocessor output of g++ -H -C -E sample-vector-code.cc if you use GCC (since its standard C++ library is free software , that you are allowed to study). And you could also look at the preprocessor output of g++ -H -C -E sample-vector-code.cc if you use GCC (since its standard C++ library is free software , that you are allowed to study). The <vector> header expands to about 10KLOC of C++ code. <vector> header 扩展为 C++ 代码的大约 10KLOC。 Glancing into that with a good editor (like emacs ) takes a dozen of minutes.用一个好的编辑器(如emacs )浏览它需要十几分钟。 Implementation details matters, even if you code above some abstraction.即使您在某些抽象之上编写代码,实现细节也很重要。

Of course it becomes invalid.当然,它变得无效。 If the memory had to be moved (which isn't always , since library authors could cheat with realloc -like implementations that don't always result in a new allocation, especially when shrinking), then the memory is at a different address.如果必须移动 memory (并非总是如此,因为库作者可能会使用类似realloc的实现作弊,这些实现并不总是会导致新的分配,尤其是在缩小时),那么 memory 位于不同的地址。 Pointers aren't magic;指针不是魔术。 they can't redirect to the logically equivalent memory on their own.他们无法自行重定向到逻辑上等效的 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM