std::basic_string<CharT,Traits,Allocator>:: operator+=
|
basic_string
&
operator
+
=
(
const
basic_string
&
str
)
;
|
(1) | (自 C++20 起为 constexpr) |
|
basic_string
&
operator
+
=
(
CharT ch
)
;
|
(2) | (自 C++20 起为 constexpr) |
|
basic_string
&
operator
+
=
(
const
CharT
*
s
)
;
|
(3) | (自 C++20 起为 constexpr) |
|
basic_string
&
operator
+
=
(
std::
initializer_list
<
CharT
>
ilist
)
;
|
(4) |
(自 C++11 起)
(自 C++20 起为 constexpr) |
|
template
<
class
StringViewLike
>
basic_string & operator + = ( const StringViewLike & t ) ; |
(5) |
(自 C++17 起)
(自 C++20 起为 constexpr) |
向字符串追加附加字符。
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; // 预留足够的存储空间以避免内存重新分配 str.reserve(50); std::cout << std::quoted(str) << '\n'; // 空字符串 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; // 相当于 str += static_cast<char>(69.96); // 通过重载 (2) 追加 'E'(ASCII 码 69), // 这可能不是本意。 // 要添加数值,请考虑使用 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++标准。
| 缺陷报告 | 应用于 | 发布时的行为 | 正确行为 |
|---|---|---|---|
| LWG 847 | C++98 | 未提供异常安全保证 | 增加了强异常安全保证 |
| LWG 2946 | C++17 | 重载 ( 5 ) 在某些情况下会导致歧义 | 通过将其改为模板来避免 |
参见
|
向末尾追加字符
(公开成员函数) |