命名空间
变体
操作

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(/* 参阅下文 */);
(C++17 起)
(C++20 起为 constexpr)

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++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 2064 C++11 非成员 swap 是 noexcept 的,与成员 swap 不一致。 noexcept 已移除

[编辑] 亦参见

交换内容
(public member function) [编辑]