std::basic_string_view::swap vs std::string::swap: What's the Difference?

2025-09-13

std::basic_string_view is a lightweight, non-owning "view" into a string. It doesn't hold its own data; it just points to a sequence of characters that already exists somewhere else. Because of this, the swap member function is extremely fast.

The swap function for std::basic_string_view simply swaps the pointers and lengths of two views. It doesn't touch the underlying string data at all. This means it's an O(1) operation—it always takes the same amount of time, no matter how long the strings are. It just swaps two small objects.

Here's an example

#include <iostream>
#include <string_view>
#include <utility> // For std::swap

int main() {
    std::string_view a = "Hello";
    std::string_view b = "World";

    std::cout << "Before swap:" << std::endl;
    std::cout << "a: " << a << std::endl;
    std::cout << "b: " << b << std::endl;

    // Use the member function swap
    a.swap(b);

    std::cout << "\nAfter swap (member function):" << std::endl;
    std::cout << "a: " << a << std::endl;
    std::cout << "b: " << b << std::endl;

    // Use the non-member std::swap function
    std::swap(a, b);

    std::cout << "\nAfter swapping back (non-member function):" << std::endl;
    std::cout << "a: " << a << std::endl;
    std::cout << "b: " << b << std::endl;

    return 0;
}

The output will be

Before swap:
a: Hello
b: World

After swap (member function):
a: World
b: Hello

After swapping back (non-member function):
a: Hello
b: World

As you can see, both a.swap(b) and std::swap(a, b) do the same thing
they just make a point to what b was pointing to, and vice versa.

The biggest pitfall with std::basic_string_view in general is the lifetime of the underlying data. Because the view doesn't own the string, you have to be absolutely sure that the string it's pointing to doesn't go away while the view is still in use. This isn't a problem with swap specifically, but it's crucial to understand when using string views.

For example, if you create a string view of a temporary std::string, the view will point to invalid memory once that string is destroyed.

#include <iostream>
#include <string>
#include <string_view>

std::string_view get_temporary_view() {
    std::string temp_string = "I'm a temporary string!";
    // DANGER! `temp_string` is destroyed when this function ends.
    return temp_string; // This is a classic "dangling view"
}

int main() {
    std::string_view bad_view = get_temporary_view();

    // The data that bad_view is pointing to has already been destroyed.
    // The behavior here is undefined and will likely crash.
    std::cout << bad_view << std::endl; 

    return 0;
}

This code is very dangerous. The std::string object temp_string is destroyed at the end of get_temporary_view(), and the std::string_view bad_view is left pointing to a dangling reference.

Sometimes, you don't just want to swap which view points to which string. You might need to actually swap the string data itself. For that, you need to use std::string.

std::string owns its data and can be modified. Its swap operation is also highly optimized and can be very fast, especially with modern C++ compilers that use "small string optimization" (SSO). Even if SSO isn't used, std::string::swap will just exchange the internal pointers, which is still very efficient.

Here's how you'd use std::string to swap the actual content

#include <iostream>
#include <string>

int main() {
    std::string a = "Hello";
    std::string b = "World";

    std::cout << "Before swap:" << std::endl;
    std::cout << "a: " << a << std::endl;
    std::cout << "b: " << b << std::endl;

    // Use the std::string member function to swap the contents
    a.swap(b);

    std::cout << "\nAfter swapping contents:" << std::endl;
    std::cout << "a: " << a << std::endl;
    std::cout << "b: " << b << std::endl;

    return 0;
}

This code is safe because std::string manages the memory for its data. The swap function here is not just swapping two views—it's efficiently swapping the owned content of the two strings.

std::string_view::swap is for swapping the views (pointers and lengths). It's always a fast, O(1) operation.

The primary pitfall with std::string_view is dangling pointers, which can happen if the underlying string data is destroyed. swap itself is not the cause, but it's important to remember this when working with views.

If you need to swap the actual string data (the characters themselves), you should use std::string and its swap member function. This is the correct and safe way to modify the string content.


cpp



Source Code Inspection: A Guide to Using std::source_location Properly (and What to Do Without It)

Let's break down the common troubles and look at some clear examples.The function std::source_location::line() returns the line number in the source file as an integer (specifically


Common Pitfalls of std::list::sort and Their Solutions

The std::list::sort function is a built-in member function that sorts the elements in a std::list in-place. This is a very common task


Common Issues and Alternatives for C++ std::basic_spanbuf Swapping

When you're working with std::basic_spanbuf and std::swap, it's easy to run into a few specific problems. A std::basic_spanbuf is a stream buffer that uses a contiguous range of memory (a span) as its underlying storage



C++ LessThanComparable: A Guide to Ordering Custom Types

In C++, the LessThanComparable named requirement is a concept that describes a type whose objects can be compared using the less-than operator (<). When a type satisfies this requirement


C++ Unordered Containers: Optimizing Performance with Load Factor, not Max Buckets

First off, what does it even do? std::unordered_multiset is a container that stores elements in "buckets" using a hash function


Exploring std::optional::emplace in C++: Common Pitfalls and Alternatives

std::optional is a great C++17 feature that represents an optional value, meaning it can either hold a value or be empty (null). The


Understanding C++ Ranges: Common join_view Pitfalls

A sentinel is a special object that acts as an endpoint for a range. Unlike a traditional iterator which points to the last element


Solving C++ std::wcscoll Locale Problems

std::wcscoll is a function in the C++ Standard Library used for locale-sensitive wide character string comparison. Unlike std::wcscmp which simply compares the numerical values of wide characters


C++ std::unordered_set::erase Common Pitfalls

The erase method in std::unordered_set is pretty straightforward, but there are a few traps that can catch you off guard


Mastering std::chrono::month_day_last::ok() in C++

A common mistake is forgetting that month_day_last doesn't validate the month on construction. The ok() method is the way to do it