Namespaces
Variants

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

From cppreference.net
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 :: value true ,则通过非限定调用非成员函数 swap 来交换分配器。否则不交换分配器(且若 get_allocator ( ) ! = other. get_allocator ( ) ,则行为未定义)。

(since C++11)

目录

参数

其他 - 用于交换内容的字符串

复杂度

常量。

异常

不抛出异常。

(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 << "Before swap:\n"
                 "a = " << a << "\n"
                 "b = " << b << "\n\n";
    a.swap(b);
    std::cout << "After swap:\n"
                 "a = " << a << "\n"
                 "b = " << b << '\n';
}

输出:

Before swap:
a = AAA
b = BBBB
After swap:
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> 的公开成员函数)