Reputation: 6560
Consider the following function:
void shrink_string(std::string& str) {
if (str.size() >= 2) {
str.resize(str.size() - 2);
}
}
I wonder if this function can be declared noexcept
(assuming C++11 standard)? I understand that the documentation does not declare .resize()
as noexcept, but that's mostly because this method can be used both for growing and shrinking a string.
Obviously, shrinking can be trivially implemented by leaving the string's capacity constant and simply reducing the internal length; at the same time resize()
may decide to reallocate anyways, in order to free up some memory -- but would it fall back to the trivial resizing if reallocation throws an error?
Upvotes: 2
Views: 635
Reputation: 11178
From the docs:
In case the container shrinks, all iterators, pointers and references to elements that have not been removed remain valid after the resize and refer to the same elements they were referring to before the call.
Therefore, resizing the vector to something smaller will not alter the memory (use shrink_to_fit
instead to (suggest a) reduce capacity to the size). That's because there is no standard way in the OS to resize the memory and force the pointers to be the same.
HeapReAlloc() for example, in Windows, may or may not return the same pointer but you can't force it to return the same.
Upvotes: 2