Table of Contents

In September our local C++ User Group started a “new year” of meetings after a little break in August. I had a pleasure to give a talk about string operations in C++17.

Here are the slides and additional comments.

The Talk  

For my book I wrote a lot of content about string_view, std::searcher and std::to_chars, std::from_chars and I wanted to make a short summary of those features.

In the talk I included some of my benchmarks and notes that were covered in my blog, for example:

Most of the time we spent discussing string_view as this feature might have a bigger impact on your code. std::searcher and low-level conversion routines are quite specialized so they won’t be used that often as views.

For example, during the discussion, we shared the experience using string views. One case is that when you refactor some existing code you’ll often find a situation where you can use views through chains of function calls, but then, at some point, you’re stuck as you have to perform conversion to string anyway.

Another thing, that was brought by Andrzej Krzemieński (from Andrzej’s C++ Blog). While string_view is supposed not to allocate any extra memory, you should be still prepared for memory allocations for exceptions.

Have a look at this code:

#include <iostream>
#include <stdexcept>
#include <string_view>

void* operator new(std::size_t n)
{
    std::cout << "new() " << n << " bytes\n";
    return malloc(n);
}

int main()
{
    std::string_view str_view("abcdef");

    try {
        for (std::size_t i = 0; true; ++i)
            std::cout << i << ": " << str_view.at(i) << '\n';
    }
    catch (const std::out_of_range& e) {
        std::cout << "Whooops. Index is out of range.\n";
        std::cout << e.what() << '\n';
    }
}

Play @Coliru

The code uses str_view.at(i) that can throw when trying to access an index out of range. When an exception is created, you’ll see some memory allocation - for the message string.
It’s probably not super often to use at, but it’s an interesting observation.

The Slides  

Let’s talks about string operations in C++17 from Bartlomiej Filipek

Summary  

The talk was my third presentation for the Cracow User Group. It’s an amazing experience, and I hope to be able to deliver more good stuff in the future :)

What is your experience with string views, searchers and low-level conversion routines? Have you played with the new features?