命名空间
变体
操作

std::swap(std::basic_string)

来自 cppreference.cn
< cpp‎ | string‎ | basic string
 
 
 
std::basic_string
常量
非成员函数
swap(std::basic_string)
I/O
比较
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
数值转换
(C++11)(C++11)(C++11)
(C++11)(C++11) 
(C++11)(C++11)(C++11)
(C++11)
(C++11)
字面量
辅助类
推导指引 (C++17)
 
定义于头文件 <string>
template< class CharT, class Traits, class Alloc >

void swap( std::basic_string<CharT, Traits, Alloc>& lhs,

           std::basic_string<CharT, Traits, Alloc>& rhs );
(C++17 前)
template< class CharT, class Traits, class Alloc >

void swap( std::basic_string<CharT, Traits, Alloc>& lhs,

           std::basic_string<CharT, Traits, Alloc>& rhs ) noexcept(/* see below */);
(自 C++17)
(constexpr 自 C++20)

std::basic_string 特化 std::swap 算法。交换 lhsrhs 的内容。

等价于 lhs.swap(rhs)

内容

[编辑] 参数

lhs, rhs - 内容将被交换的字符串

[编辑] 返回值

(无)

[编辑] 复杂度

常数。

异常

noexcept 规范:  
noexcept(noexcept(lhs.swap(rhs)))
(自 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";
 
    std::swap(a, 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++ 标准。

DR 应用于 已发布行为 正确行为
LWG 2064 C++11 非成员 swap 为 noexcept 且与成员 swap 不一致 noexcept 已移除

[编辑] 参见

交换内容
(公开成员函数) [编辑]