Is vector::shrink_to_fit allowed to reallocate?

瘦欲@ 提交于 2020-06-11 17:50:18

问题


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."

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...


回答1:


I agree, the intention is obviously that shrink_to_fit() can reallocate, so it should be allowed to invalidate iterators.

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.

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.



来源:https://stackoverflow.com/questions/13912507/is-vectorshrink-to-fit-allowed-to-reallocate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!