- string[meta header]
- std[meta namespace]
- basic_string[meta class]
- function[meta id-type]
void swap(basic_string& str); // (1) C++98
void swap(basic_string& str) noexcept
(allocator_traits<Allocator>::propagate_on_container_swap::value
|| allocator_traits<Allocator>::is_always_equal::value); // (1) C++17
constexpr void swap(basic_string& str) noexcept
(allocator_traits<Allocator>::propagate_on_container_swap::value
|| allocator_traits<Allocator>::is_always_equal::value); // (1) C++20他のbasic_stringオブジェクトとデータを入れ替える。
*thisの内容をstrと交換する。
なし
定数時間
- swapされるコンテナの要素を指す参照、ポインタ、イテレータを無効化しない。
- ただし、
end()が指すイテレータはどの要素も指していないが、無効になることがある。
- ただし、
#include <iostream>
#include <string>
int main()
{
std::string a = "hello";
std::string b = "world";
a.swap(b);
std::cout << a << std::endl;
std::cout << b << std::endl;
}- swap[color ff0000]
world
hello
- N4258 Cleaning-up noexcept in the Library, Rev 3
noexcept追加の経緯となる提案文書
- P0980R1 Making
std::stringconstexpr - LWG Issue 765. More on iterator validity
- C++11で、
swap()が参照・ポインタ・イテレータを無効化しないという要件に対して、「end()が返すイテレータはどの要素も指していないため、無効化されることがある」という注記が追加された
- C++11で、