std::basic_string::swap - cppreference.com

##### cppreference.com

##### Search

Create account

##### Namespaces

- Page
- Discussion

##### Variants

##### Views

- View
- Edit
- History

##### Actions

# std::basic_string::swap

From cppreference.com
< cpp‎ | string‎ | basic string

void swap( basic_string& other ); |  |

Exchanges the contents of the string with those of `other`. All iterators and references may be invalidated.

### [edit] Parameters

other | - | string to exchange the contents with

### [edit] Return value

(none)

### [edit] Exceptions

`noexcept` specification: noexcept(std::allocator_traits<Allocator>::propagate_on_container_swap::value || std::allocator_traits<Allocator>::is_always_equal::value) | (since C++17)

### [edit] Example

Run this code

    #include <string>
    #include <iostream>

    int main()
    {
        std::string a = "AAA";
        std::string b = "BBB";

        std::cout << "before swap" << '\n';
        std::cout << "a: " << a << '\n';
        std::cout << "b: " << b << '\n';

        a.swap(b);

        std::cout << "after swap" << '\n';
        std::cout << "a: " << a << '\n';
        std::cout << "b: " << b << '\n';
    }

Output:

    before swap
    a: AAA
    b: BBB
    after swap
    a: BBB
    b: AAA

### [edit] Complexity

Constant.

Retrieved from "http://en.cppreference.com/mwiki/index.php?title=cpp/string/basic_string/swap&oldid=73741"
Category:

- conditionally noexcept