Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::basic_string<CharT,Traits,Allocator>::shrink_to_fit

      From cppreference.com
      <cpp‎ |string‎ |basic string
       
       
       
      std::basic_string
       
      void shrink_to_fit();
      (constexpr since C++20)

      Requests the removal of unused capacity.

      It is a non-binding request to reducecapacity() tosize(). It depends on the implementation if the request is fulfilled.

      If (and only if) reallocation takes place, all pointers, references, and iterators are invalidated.

      Contents

      [edit]Complexity

      Linear in the size of the string.

      [edit]Notes

      In libstdc++,shrink_to_fit() isnot available in C++98 mode.

      [edit]Example

      Run this code
      #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';}

      Possible output:

      GCC output:Size of std::string is 32 bytesDefault-constructed capacity is 15 and size 0Capacity after 42 appends is 240 and size 168Capacity after clear() is 240 and size 0Capacity after shrink_to_fit() is 15 and size 0 clang output (with -stdlib=libc++):Size of std::string is 24 bytesDefault-constructed capacity is 22 and size is 0Capacity after 42 appends is 191 and size is 168Capacity after clear() is 191 and size is 0Capacity after shrink_to_fit() is 22 and size is 0

      [edit]Defect reports

      The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

      DRApplied toBehavior as publishedCorrect behavior
      LWG 755C++98std::string lacked explicit shrink-to-fit operationsprovided
      LWG 2223C++981. references, pointers, and iterators were not invalidated
      2. there was no complexity requirement
      1. they may be invalidated
      2. required to be linear

      [edit]See also

      returns the number of characters
      (public member function)[edit]
      returns the number of characters that can be held in currently allocated storage
      (public member function)[edit]
      changes the number of characters stored
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/string/basic_string/shrink_to_fit&oldid=177699"

      [8]ページ先頭

      ©2009-2025 Movatter.jp