Skip to content

1.4 Exchanging Values Without Using Temporary Variables

RobStewart edited this page May 15, 2013 · 2 revisions

Problem

Given two string variables, swap the contents without using a temporary variable.

Solution

std::string provides the swap() member function for this purpose:

std::string one{"This is string one"};
std::string two("This is string two"};
one.swap(two);

Discussion

std::string::swap() exchanges the internal state of two non-const instances without copying any data.

See Also

Clone this wiki locally