Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is vector::shrink_to_fit allowed to reallocate?

Tags:

c++

std

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

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

like image 738
soulie Avatar asked Dec 17 '12 10:12

soulie


1 Answers

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.

like image 167
Jonathan Wakely Avatar answered Oct 17 '22 10:10

Jonathan Wakely