In C++, std::string::swap() exchanges the contents of two strings.
After the call, each string holds what the other used to hold. Include <string>.
This is a member of std::string. A string grows as you append, stores characters contiguously, and can reallocate—after growth, old iterators and references may be invalid. Prefer at() when you want bounds checks; remember find returns npos when missing.
Syntax
Call as a member or with std::swap.
C++
a.swap(b);
std::swap(a, b);
Call
What it does
a.swap(b)
Exchange contents of a and b.
std::swap(a, b)
Usually calls the member swap.
Swap does not throw for std::string with the default allocator.
Library declarations
C++
void swap(string& other) noexcept;
Parameters
Parameter
Description
other
The other string to exchange with.
Return Value
Return Value
Description
void
No return value.
C++ Examples
Example 1 — Basic swap()
Exchange two words.
C++
#include <iostream>
#include <string>
int main() {
std::string a = "left";
std::string b = "right";
a.swap(b);
std::cout << a << ' ' << b << '\\n';
return 0;
}
Output
right left
How It Works
a starts as left, b as right.
swap exchanges their contents.
Printed order shows the exchange.
Example 2 — Using std::swap
Same effect via std::swap.
C++
#include <iostream>
#include <string>
#include <utility>
int main() {
std::string x = "1";
std::string y = "2";
std::swap(x, y);
std::cout << x << y << '\\n';
return 0;
}
Output
21
How It Works
std::swap finds the efficient string swap.
Values are exchanged.
Output is 21.
Example 3 — Swap With Self
Swapping a string with itself is a no-op.
C++
#include <iostream>
#include <string>
int main() {
std::string s = "same";
s.swap(s);
std::cout << s << '\\n';
return 0;
}
Output
same
How It Works
Self-swap is allowed.
Contents stay identical.
Useful to know it is safe.
Frequently Asked Questions
It exchanges the contents of two strings.
Usually yes—often pointer exchange rather than copying characters.
For std::string with equal allocators it is noexcept.
Either. std::swap typically calls the member.
Not typically for large strings; implementations exchange buffers.