简体   繁体   English

C++ std::vector<t*> 如果您持有指向指针元素的指针,它会在调整大小时失效吗?</t*>

[英]C++ std::vector<T*> if you hold a pointer to a pointer element, does it become invalidated upon resize?

Let us say I create std::vector<int*> myVec;假设我创建了std::vector<int*> myVec; and reserve 100 entries and populate the vector with values so that all 100 elements have valid pointers.并保留 100 个条目并用值填充向量,以便所有 100 个元素都有有效的指针。 I then cache a pointer to one of the elements,然后我缓存一个指向其中一个元素的指针,

int * x = myVec[60];

Then, if I append another int * which triggers a resize along with a move due to heap fragmentation, does the previous pointer to a pointer become invalidated or does it point to the new location in memory?然后,如果我 append 另一个int *由于堆碎片而触发调整大小以及移动,那么指向指针的前一个指针是否失效或指向 memory 中的新位置?

If my memory servers me correct, if the example were to std::vector<int> myVecTwo with the same conditions as above and I stored a ptr like如果我的 memory 服务我是正确的,如果示例是std::vector<int> myVecTwo具有与上述相同的条件并且我存储了一个类似

int * x = &myVecTwo[60]; 

and proceeded to append and resize, that pointer would be invalided.并继续到 append 并调整大小,该指针将无效。

So, my question is as follows.所以,我的问题如下。 Would the pointer to the pointer become invalidated?指向指针的指针会失效吗? I am no longer certain because of the new C++ std functionality of is_trivially_copyable and whether the std::vector makes use of such functionality or POD checks.由于 is_trivially_copyable 的新C++ std 功能以及 std::vector 是否使用此类功能或 POD 检查,我不再确定。

Would the pointer by invalidated in C++11?指针会在 C++11 中失效吗?

No.不。

As you showed, after the reallocation, the pointers to the elements of the vector , like int * x = &myVecTwo[60];正如您所展示的,在重新分配之后,指向vector元素的指针,例如int * x = &myVecTwo[60]; would be invalidated.将失效。 After the reallocation, the elements themselves would be copied, but the object pointed by the element pointers won't be affected, then for int * x = myVec[60];重新分配后,元素本身会被复制,但元素指针指向的 object 不受影响,则 for int * x = myVec[60]; , after the reallocation x is still pointing to the same object, which has nothing to do with the reallocation of the vector . ,重新分配后x仍然指向同一个object,这与vector的重新分配无关。

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

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