是否允许vector :: shrink_to_fit重新分配? [英] Is vector::shrink_to_fit allowed to reallocate?
问题描述
此成员函数在标准中没有定义的作用(仅备注),如果不允许重新分配,则其使用将受到限制。但是我在标准中发现的唯一适用于23.2.1 / 11的段落:
This member function, that has no defined effect in the standard (only remarks), would have limited use if not allowed to reallocate. But the only paragraph I found in the standard that seems to apply would be 23.2.1/11:
或通过在其他函数方面定义一个函数),调用容器成员函数或将容器作为参数传递给库函数,都不应使对该容器内对象的迭代器或更改其值无效。
"Unless otherwise specified (either explicitly or by defining a function in terms of other functions), invoking a container member function or passing a container as an argument to a library function shall not invalidate iterators to, or change the values of, objects within that container."
由于重新分配使迭代器无效,这是否意味着shrink_to_fit无法正式重新分配?如果是这样,则该函数仅对减少容量不会重新分配的实现有效(如果有)...
Since reallocations invalidate iterators, would this imply that shrink_to_fit cannot formally reallocate? If so, the function could only have effect on implementations where reducing capacity does not reallocate, if any...
推荐答案
我同意,其目的显然是 shrink_to_fit()
可以重新分配,因此应该允许它使迭代器无效。
I agree, the intention is obviously that shrink_to_fit()
can reallocate, so it should be allowed to invalidate iterators.
它仅在实现为分配器提供类似于 realloc()
的功能的情况下才可能兑现请求,该功能可确保在缩小块时不移动内存,这不会使内存无效迭代器。但是,我不认为这是我们的意图,正如最近添加的要求 T
是向量中的 MoveInsertable
,因为该要求仅在元素移至新元素时才有意义
It would be possible to only honour the request if the implementation provides a realloc()
-like feature for allocators that guaranteed not to move the memory when shrinking the block, which would not invalidate iterators. But I don't believe that's what's intended, as implied by the recently-added requirement that T
is MoveInsertable
into the vector, because that requirement is only relevant if the elements are moved to new locations, which would invalidate iterators.
我认为您应该提交问题以澄清问题, shrink_to_fit()
会使迭代器无效。该问题将适用于 basic_string
,双端队列
和 vector
。
I think you should submit an issue to get it clarified that shrink_to_fit()
can invalidate iterators. The issue would apply to basic_string
, deque
and vector
.
这篇关于是否允许vector :: shrink_to_fit重新分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!