std::basic_string<CharT,Traits,Allocator>::reserve_C++中文网

(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 大于 max_size() 则抛出 std::length_error

可能抛出任何 std::allocator_traits<Allocator>::allocate() 所抛的异常,如 std::bad_alloc

复杂度

至多与 string 的 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());
}

参阅