问题描述
当载体需要更多的内存,它会重新分配内存在某个地方,我不知道在哪里!然后指针变得无效,对此有什么好的解释吗?
我的意思是他们去哪里,我的容器发生了什么? (非链接列表)
简短答案:一切都会好起来。
中回答:向向量中添加元素或从向量中删除元素会使所有迭代器失效,引用/指针(可能除了从后面删除)。就那么简单。不要引用任何旧的迭代器,并在这样的操作后获得新的迭代器。示例:
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);
现在 a
, b
和 c
都无效:您不能使用 a
,并且您无法取消引用 b
或 c
。
长回答:向量会跟踪动态内存。当内存耗尽时,它在其他地方分配一个新的更大的块,并复制(或移动)所有的旧元素(然后释放旧的内存,破坏旧的对象)。内存分配和释放由 allocator (通常 std :: allocator
)完成,后者通常调用 :: operator new()
来获取内存,通常调用 malloc()
。详细信息可能会有所不同,具体取决于您的平台。在任何情况下,任何以前保存的引用,指针或迭代器不再有效(可能是因为它们指的是现在释放的内存,虽然它没有在标准中指定为什么它们无效) / p>
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);
Now a
, b
and c
are all invalid: You cannot use a
, and you cannot dereference b
or c
.
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).
这篇关于当向量需要更多的内存和realocate内存时,指针会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!