当向量需要更多内存并重新分配内存时,指针会发生什么? [英] What happen to pointers when vectors need more memory and realocate memory?

查看:33
本文介绍了当向量需要更多内存并重新分配内存时,指针会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当vector需要更多内存时,它会在某处重新分配内存,我还不知道在哪里!然后指针变得无效,对此有什么好的解释吗?

When vector needs more memory it will reallocate memory somewhere, I don't know where yet! and then pointers become invalid, is there any good explanation on this?

我的意思是他们去了哪里,我的容器怎么办?(不是链表的)

I mean where they go, what happen to my containers? ( not linked list ones )

推荐答案

简短回答:一切都会好起来的.别担心,回去工作吧.

Short answer: Everything will be fine. Don't worry about this and get back to work.

中等答案:将元素添加到向量或从向量中删除它们会使所有迭代器和引用/指针无效(可能除了从后面删除).就那么简单.不要引用任何旧的迭代器并在这样的操作后获取新的迭代器.示例:

Medium answer: Adding elements to or removing them from a vector invalidates all iterators and references/pointers (possibly with the exception of removing from the back). Simple as that. Don't refer to any old iterators and obtain new ones after such an operation. Example:

std::vector<int> v = get_vector();

int & a = v[6];
int * b = &v[7];
std::vector<int>::iterator c = v.begin();
std::advance(it, 8);

v.resize(100);

现在abc都无效:你不能使用a,并且您不能取消引用 bc.

Now a, b and c are all invalid: You cannot use a, and you cannot dereference b or c.

长答案:向量跟踪动态内存.当内存耗尽时,它会在别处分配一个新的更大的块并复制(或移动)所有旧元素(然后释放旧内存,销毁旧对象).内存分配和释放由 allocator(通常是 std::allocator)完成,它通常会调用 ::operator new()code> 来获取内存,这通常会调用 malloc().详细信息可能会有所不同,具体取决于您的平台.在任何情况下,任何以前持有的引用、指针或迭代器都不再有效(大概是因为它们指的是现在释放的内存,尽管标准中没有指定为什么它们是无效的).

Long answer: The vector keeps track of dynamic memory. When the memory is exhausted, it allocates a new, larger chunk elsewhere and copies (or moves) all the old elements over (and then frees up the old memory, destroying the old objects). Memory allocation and deallocation is done by the allocator (typically std::allocator<T>), which in turn usually invokes ::operator new() to fetch memory, which in turn usually calls malloc(). Details may vary and depend on your platform. In any event, any previously held references, pointers or iterators are no longer valid (presumably because they refer to the now-freed memory, though it's not specified in the standard why they're invalid).

这篇关于当向量需要更多内存并重新分配内存时,指针会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆