std::basic_string<CharT,Traits,Allocator>:: shrink_to_fit
| Classes | ||||
|
(C++17)
|
||||
|
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
void
shrink_to_fit
(
)
;
|
(constexpr начиная с C++20) | |
Запрашивает удаление неиспользуемой ёмкости.
Это необязательный запрос на уменьшение capacity() до size() . Зависит от реализации, будет ли запрос выполнен.
Если (и только если) происходит перераспределение памяти, все указатели, ссылки и итераторы становятся недействительными.
Содержание |
Сложность
Линейно от размера строки.
Примечания
В libstdc++,
shrink_to_fit()
недоступен
в режиме C++98.
Пример
#include <iostream> #include <string> int main() { std::string s; std::cout << "Size of std::string is " << sizeof s << " bytes\n" << "Default-constructed capacity is " << s.capacity() << " and size is " << s.size() << '\n'; for (int i = 0; i < 42; i++) s.append(" 42 "); std::cout << "Capacity after 42 appends is " << s.capacity() << " and size is " << s.size() << '\n'; s.clear(); std::cout << "Capacity after clear() is " << s.capacity() << " and size is " << s.size() << '\n'; s.shrink_to_fit(); std::cout << "Capacity after shrink_to_fit() is " << s.capacity() << " and size is " << s.size() << '\n'; }
Возможный вывод:
GCC output: Size of std::string is 32 bytes Default-constructed capacity is 15 and size 0 Capacity after 42 appends is 240 and size 168 Capacity after clear() is 240 and size 0 Capacity after shrink_to_fit() is 15 and size 0 clang output (with -stdlib=libc++): Size of std::string is 24 bytes Default-constructed capacity is 22 and size is 0 Capacity after 42 appends is 191 and size is 168 Capacity after clear() is 191 and size is 0 Capacity after shrink_to_fit() is 22 and size is 0
Отчеты о дефектах
Следующие отчеты об изменениях в поведении, содержащие описания дефектов, были применены ретроактивно к ранее опубликованным стандартам C++.
| DR | Applied to | Behavior as published | Correct behavior |
|---|---|---|---|
| LWG 755 | C++98 |
std::string
lacked explicit shrink-to-fit operations
|
provided |
| LWG 2223 | C++98 |
1. references, pointers, and iterators were not invalidated
2. there was no complexity requirement |
1. they may be invalidated
2. required to be linear |
Смотрите также
|
возвращает количество символов
(public member function) |
|
|
возвращает количество символов, которое может быть размещено в текущем выделенном хранилище
(public member function) |
|
|
изменяет количество хранимых символов
(public member function) |