名前空間
変種
操作

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

提供: cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
(1)
void reserve( size_type new_cap = 0 );
(C++20未満)
constexpr void reserve( size_type new_cap );
(C++20以上)
void reserve();
(2) (C++20以上)
(非推奨)
1) 記憶域の確保を適切に管理できるように、サイズ変更の予定を std::basic_string に知らせます。
  • new_cap が現在の capacity() より大きい場合、新しい記憶域が確保され、 capacity()new_cap より大きくまたは等しくなります。
  • new_cap が現在の capacity() より小さい場合、これは拘束力のない縮小要求です。
  • new_cap が現在の size() より小さい場合、これは拘束力のない shrink_to_fit() と同等な (C++11以上) shrink-to-fit 要求です。
(C++20未満)
  • new_cap が現在の capacity() より小さい場合、効果はありません。
(C++20以上)
容量変更が行われた場合、すべてのイテレータと参照 (終端イテレータを含む) が無効化されます。
2) 引数なしの reserve 呼び出しは拘束力のない shrink-to-fit 要求です。 この呼び出しの後、 capacity()size() より大きいまたは等しい未規定の値になります。
(C++20以上)

目次

[編集] 引数

new_cap - 文字列の新しい容量

[編集] 戻り値

(なし)

[編集] 例外

new_capmax_size() より大きい場合、 std::length_error を投げます。

std::bad_alloc などの std::allocator_traits<Allocator>::allocate() によって投げられるあらゆる例外も投げるかもしれません。

[編集] 計算量

文字列の size() にほぼ比例。

[編集]

#include <cassert>
#include <string>
 
int main()
{
    std::string s;
    std::string::size_type new_capacity{ 100u };
    assert(new_capacity > s.capacity());
 
    s.reserve(new_capacity);
    assert(new_capacity <= s.capacity());
}


[編集] 関連項目

現在確保されている記憶域に保持することができる文字数を返します
(パブリックメンバ関数) [edit]