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

来自cppreference.com
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
 
void swap( basic_string& other );
(C++17 前)
void swap( basic_string& other )noexcept(/* 见下文 */);
(C++17 起)
(C++20 起为 constexpr)

交换字符串与 other 的内容。所有迭代器和引用都可能会失效。

如果 std::allocator_traits<allocator_type>::propagate_on_container_swap::valuetrue,那么使用对非成员 swap 进行无限定调用来交换这些分配器。否则,不交换它们(且若 get_allocator()!= other.get_allocator() 则其行为未定义)。

(C++11 起)

目录

[编辑]参数

other - 要与之交换内容的字符串

[编辑]复杂度

常数。

[编辑]异常

不会抛出异常。

(C++11 前)

只有在行为未定义的情况下才有可能会抛出异常。

如果因为任何原因抛出了异常,那么此函数无效果(强异常安全保证)。

(C++11 起)


noexcept 说明:  
noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value||
         std::allocator_traits<Allocator>::is_always_equal::value)
(C++17 起)

[编辑]示例

#include <iostream>#include <string>   int main(){std::string a ="AAA";std::string b ="BBBB";   std::cout<<"交换前:\n""a = "<< a <<"\n""b = "<< b <<"\n\n";   a.swap(b);   std::cout<<"交换后:\n""a = "<< a <<"\n""b = "<< b <<'\n';}

输出:

交换前: a = AAA b = BBBB   交换后: a = BBBB b = AAA

[编辑]缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 出版时的行为 正确行为
LWG 403 C++98 swap() 可能会抛出异常 不会抛出异常
LWG 535 C++98 交换字符串不会保留字符顺序 也保留字符顺序
LWG 2151
(P1148R0)
C++11 在分配器不相等且不传播的情况下不会抛出异常 此时行为未定义

[编辑]参阅

交换两个对象的值
(函数模板)[编辑]
交换两个范围的元素
(函数模板)[编辑]
交换内容
(std::basic_string_view<CharT,Traits> 的公开成员函数)[编辑]
close