Swapping C++ Strings: A Guide to std::swap and Its Alternatives

2025-09-17

While std::swap is generally straightforward, you might encounter a few common issues, especially when dealing with older code or different data types.

One frequent problem is trying to swap two strings that have different character types. The compiler will throw an error because std::basic_string is a template class, and std::swap is defined for a specific template instantiation.

Example of the problem

#include <string>
#include <string_view>

int main() {
    std::string str1 = "hello";
    std::string_view sv1 = "world";

    // This will cause a compilation error because std::string and std::string_view are different types.
    // std::swap(str1, sv1); // ERROR!

    return 0;
}

Why it happens
std::string_view is a non-owning reference to a string, not a full string object. It's meant for read-only access and can't be modified in place. std::swap requires two objects of the same std::basic_string type.

You can't swap a std::string with a const std::string. The std::swap function requires non-const lvalue references because it needs to modify both objects.

Example of the problem

#include <string>

int main() {
    std::string str1 = "hello";
    const std::string const_str = "world";

    // This will cause a compilation error because const_str is const.
    // std::swap(str1, const_str); // ERROR!

    return 0;
}

Why it happens
The const keyword tells the compiler that the object cannot be changed. Since std::swap needs to modify its arguments, this is a violation of the const contract.

While std::swap is usually the best choice, here are some alternatives you might see or need to use in specific situations.

Every std::basic_string object has its own member function swap(). This method is functionally identical to the global std::swap but is called directly on one of the string objects. It's often used in older code or when clarity is preferred.

Example

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Apple";
    std::string str2 = "Banana";

    std::cout << "Before swap: str1 = " << str1 << ", str2 = " << str2 << std::endl;

    // Using the member function
    str1.swap(str2);

    std::cout << "After swap: str1 = " << str1 << ", str2 = " << str2 << std::endl;

    return 0;
}

Advantages
This is a clear and direct way to swap. It's a member function, so it's guaranteed to be available and work correctly for std::string objects.

Before std::swap became widely used and optimized, it was common to manually swap strings using a temporary variable. This method works but is generally less efficient for large strings because it involves two copies and a destruction.

Example

#include <iostream>
#include <string>

int main() {
    std::string str1 = "Apple";
    std::string str2 = "Banana";

    std::cout << "Before swap: str1 = " << str1 << ", str2 = " << str2 << std::endl;

    // Manual swapping using a temporary variable
    std::string temp = str1;
    str1 = str2;
    str2 = temp;

    std::cout << "After swap: str1 = " << str1 << ", str2 = " << str2 << std::endl;

    return 0;
}

Disadvantages
This is generally not recommended for C++ std::string objects because it can be slower. The assignment operator (=) for std::string performs a deep copy of the underlying character data. In contrast, std::swap just swaps a few internal pointers, which is much faster.


cpp



Troubleshooting std::hash in C++

A common misconception is that std::hash<std::type_index> will magically hash any custom type you throw at it. This isn't the case! std::type_index works on types


C++ Random Number Generation: A Guide to std::negative_binomial_distribution

The std::negative_binomial_distribution::operator() is used to generate random numbers based on a negative binomial probability distribution


Common Issues and Alternatives for std::ranges::join_view::end

Here's an explanation of some common issues and how to work around them, along with alternative methods.One of the most common issues with std::ranges::join_view::end is when it's used with an outer range that is not a forward range or a bidirectional range



The C++ Ranges common_view::base Member Function Explained

First, let's break down the name.std::ranges This is the namespace for the C++20 Ranges library, which provides a modern


Smart Pointers vs. std::scoped_allocator_adaptor::allocate: A Practical Comparison

Hi there! Let's talk about some common issues and alternatives for dynamic memory management in C++, specifically regarding std::scoped_allocator_adaptor::allocate


From Deprecated to Dynamic: C++ String Conversion with ICU & Platform APIs

One of the most frequent problems you'll encounter is a compilation error because std::wstring_convert and std::wbuffer_convert are no longer part of the standard library in C++17 and beyond


C++ Standard Library's Utility Header: Pitfalls and Alternatives

The <utility> header in C++ is a powerful tool that provides several essential utilities, but sometimes you can run into issues


Troubleshooting std::expected::transform in C++

std::expected is a C++17 library feature that represents a value that might either be a valid result or contain an error


Here are a few title options based on our discussion about std::atomic::fetch_xor:

std::atomic::fetch_xor is an atomic read-modify-write operation. It performs a bitwise XOR on the value of an atomic variable with a given argument


C++ std::map::emplace: Common Pitfalls and Modern Alternatives

At its core, std::map::emplace is about one thing efficiency. Instead of creating an object outside the map and then copying or moving it in