std::basic_string<CharT,Traits,Allocator>::operator+=
来自 cppreference.cn
< cpp | string | basic string
basic_string& operator+=( const basic_string& str ); |
(1) | (constexpr since C++20) |
basic_string& operator+=( CharT ch ); |
(2) | (constexpr since C++20) |
basic_string& operator+=( const CharT* s ); |
(3) | (constexpr since C++20) |
basic_string& operator+=( std::initializer_list<CharT> ilist ); |
(4) | (since C++11) (constexpr since C++20) |
template< class StringViewLike > basic_string& operator+=( const StringViewLike& t ); |
(5) | (since C++17) (constexpr since C++20) |
向字符串追加字符。
1) 追加字符串 str。
2) 追加字符 ch。
3) 追加由 s 指向的空终止字符字符串。
4) 追加初始化列表 ilist 中的字符。
5) 隐式地将 t 转换为字符串视图 sv,如同 std::basic_string_view<CharT, Traits> sv = t;,然后如同通过 append(sv) 追加字符串视图 sv 中的字符。
仅当 std::is_convertible_v<const StringViewLike&,
std::basic_string_view<CharT, Traits>> 为 true 且 std::is_convertible_v<const StringViewLike&, const CharT*> 为 false 时,此重载才参与重载决议。
std::basic_string_view<CharT, Traits>> 为 true 且 std::is_convertible_v<const StringViewLike&, const CharT*> 为 false 时,此重载才参与重载决议。
内容 |
[编辑] 参数
str | - | 要追加的字符串 |
ch | - | 要追加的字符值 |
s | - | 指向要追加的空终止字符字符串的指针 |
ilist | - | std::initializer_list,包含要追加的字符 |
t | - | 对象(可转换为 std::basic_string_view),包含要追加的字符 |
[编辑] 返回值
*this
[编辑] 复杂度
没有标准的复杂度保证,典型实现的行为类似于 std::vector::insert()。
[编辑] 异常
如果操作会导致 size()
超过 max_size()
,则抛出 std::length_error。
如果由于任何原因抛出异常,则此函数没有效果(强异常安全保证)。
[编辑] 注释
重载 (2) 可以接受任何隐式转换为 CharT
的类型。对于 std::string
,其中 CharT
是 char,可接受的类型集包括所有算术类型。这可能具有意外的效果。
[编辑] 示例
运行此代码
#include <iomanip> #include <iostream> #include <string> int main() { std::string str; // reserve sufficient storage space to avoid memory reallocation str.reserve(50); std::cout << std::quoted(str) << '\n'; // empty string str += "This"; std::cout << std::quoted(str) << '\n'; str += std::string(" is "); std::cout << std::quoted(str) << '\n'; str += 'a'; std::cout << std::quoted(str) << '\n'; str += {' ', 's', 't', 'r', 'i', 'n', 'g', '.'}; std::cout << std::quoted(str) << '\n'; str += 69.96; // Equivalent to str += static_cast<char>(69.96); // 'E' (ASCII code 69) is appended by overload (2), // which might not be the intent. // To add a numeric value, consider std::to_string(): str += std::to_string(1729); std::cout << std::quoted(str) << '\n'; }
输出
"" "This" "This is " "This is a" "This is a string." "This is a string.E1729"
[编辑] 缺陷报告
以下行为更改缺陷报告被追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布的行为 | 正确的行为 |
---|---|---|---|
LWG 847 | C++98 | 没有异常安全保证 | 添加了强异常安全保证 |
LWG 2946 | C++17 | 重载 (5) 在某些情况下引起歧义 | 通过使其成为模板来避免 |
[编辑] 参见
将字符追加到末尾 (公共成员函数) |