Articles & Books

An Informal Comparison of the Three Major Implementations of std::string -- Raymond Chen

RaymondChen_5in-150x150.jpgWe saw some time ago that the three major implementations of std::string are all quite different...

An informal comparison of the three major implementations of std::string

by Raymond Chen

From the article:

In the original version of this article, I got the sense of the “small/large” bit backward in the clang implementation. This in turn led to redoing the code generation and new code golfing results.

We’ll compare these versions based on the complexity of some commonly-used operations.

Adding State to the Update Notification Pattern, Part 7 -- Raymond Chen

RaymondChen_5in-150x150.jpgLast time, we refined our change counter-based stateful but coalescing update notification. This version still relies on a UI thread to do two things: (1) make the final final change counter check and the subsequent callback atomic, and (2) to serialize the callbacks.

Adding State to the Update Notification Pattern, Part 7

by Raymond Chen

From the article:

If we don’t have a UI thread, then we open a race condition.

 
class EditControl
{
    ⟦ ... existing class members ... ⟧

    std::atomic<unsigned> m_latestId;
};

winrt::fire_and_forget
EditControl::TextChanged(std::string text)
{
    auto lifetime = get_strong();

    auto id = m_latestId.fetch_add(1, std::memory_order_relaxed);

    co_await winrt::resume_background();

    if (!IsLatestId(id))) co_return;

    std::vector<std::string> matches;
    for (auto&& candidate : FindCandidates(text)) {
        if (candidate.Verify()) {
            matches.push_back(candidate.Text());
        }
        if (!IsLatestId(id))) co_return;
    }

    // co_await winrt::resume_foreground(Dispatcher());

    if (!IsLatestId(id))) co_return;

    SetAutocomplete(matches);
}

Understand Internals of std::expected -- Bartlomiej Filipek

BartlomiejFilipek-expected.pngIn the article about std::expected, I introduced the type and showed some basic examples, and in this text, you’ll learn how it is implemented.

Understand Internals of std::expected

by Bartlomiej Filipek

From the article:

In short, std::expected should contain two data members: the actual expected value and the unexpected error object. So, in theory, we could use a simple structure:

template <class _Ty, class _Err> 
struct expected {  
     /*... lots of code ... */  
     _Ty _Value;  
     _Err _Unexpected; 
}; 

However, there are better solutions than this. Here are some obvious issues for our “struct” approach.

  • The size of the object is the sum of the Value type and the Error type (plus padding if needed).
  • Two data members are “active” and initialized, which might not be possible - for example, what if the Value type has no default constructor? The Standard requires that std::expected" holds either a value of type Tor an error of typeE` within its storage.
  • We’d have to guarantee that _Ty cannot be a reference type or an array type; it must be a Destructible Type.
  • Similarly for the _Err type we have to guarantee that it’s also Destructible, and must be a valid template argument for std::unexpected (so not an array, non-object type, nor cv-qualified type).
  • Plus, we’d have to write a lot of code that creates an API for the type

C++ programmer's guide to undefined behavior: part 1 of 11

Your attention is invited to the first part of an e-book on undefined behavior. This is not a textbook, as it's intended for those who are already familiar with C++ programming. It's a kind of C++ programmer's guide to undefined behavior and to its most secret and exotic corners. The book was written by Dmitry Sviridkin and edited by Andrey Karpov.

C++ programmer's guide to undefined behavior: part 1 of 11

by Dmitry Sviridkin

From the article:

Many modern programming languages, especially newer ones, forbid implicit type conversions. So, in Rust, Haskell, or Kotlin, we can't just use float and int in the same arithmetic expression without explicitly stating in the code to convert one to the other. Python isn't as strict but still keeps strings, characters, and numbers from mixing. C++ doesn't forbid implicit conversion, which leads to a lot of erroneous code. Moreover, such code can contain both defined (but unexpected) and undefined behavior.

Qt and Trivial Relocation (Part 1) -- Giuseppe D'Angelo

sso1.pngIn Qt 4, container classes like QVector introduced an optimization that transformed certain operations on contained objects into efficient byte-level manipulations. By identifying types that can be safely moved via a simple memory copy, Qt was able to streamline reallocations for specific data types like int and QString. This article explores the concept of trivial relocation, how Qt leverages it for optimized data manipulation, and the implications for different container structures and data types.

Qt and Trivial Relocation (Part 1)

by Giuseppe D'Angelo

From the article:

The container classes introduced in Qt 4 (Tulip, for the aficionados) had an interesting optimization: the ability to turn certain operations on the contained objects into byte-level manipulations.

Example: vector reallocation

Consider the reallocation of a QVector<T>: when the vector is full and we want to insert a new value (of type T), the vector has to allocate a bigger block of memory.

vector_realloc_step0.png

Error on verge of extinction, or why I put if (x = 42) in Red List of C & C++ bugs

If we ask a programmer what bugs are the most common in C and C++ code, they'll name a null pointer dereference, undefined behavior, array overrun, and other typical error patterns. They may name an accidental assignment in condition as well. However, let's see if this error is common today.

Error on verge of extinction, or why I put if (x = 42) in Red List of C & C++ bugs

by Andrey Karpov

From the article:

Because of this bug, developers invented the Yoda notation: a programming style where the constant is placed on the left side of the comparison operator. This style was meant to prevent a typo. If a programmer writes = instead of ==, the code won't compile.

Adding State to the Update Notification Pattern, Part 6 -- Raymond Chen

RaymondChen_5in-150x150.jpgLast time, we built a stateful but coalescing update notification using a change counter to identify which request is the latest one, but noted that it does unnecessary work. Let’s see if we can avoid the unnecessary work.

Adding State to the Update Notification Pattern, Part 6

by Raymond Chen

From the article:

We could add some early exits to abandon the work if we notice that we are no longer doing work on behalf of the most recent text change. It means that we have to switch the change counter variable to a std::atomic since we will be reading the variable from the background thread at the same time the UI thread may be modifying it.

 
class EditControl
{
    ⟦ ... existing class members ... ⟧

    std::atomic<unsigned> m_latestId;
};

winrt::fire_and_forget
EditControl::TextChanged(std::string text)
{
    auto lifetime = get_strong();

    auto id = m_latestId.fetch_add(1, std::memory_order_relaxed);

    co_await winrt::resume_background();

    if (!IsLatestId(id))) co_return;

    std::vector<std::string> matches;
    for (auto&& candidate : FindCandidates(text)) {
        if (candidate.Verify()) {
            matches.push_back(candidate.Text());
        }
        if (!IsLatestId(id))) co_return;
    }

    co_await winrt::resume_foreground(Dispatcher());

    if (!IsLatestId(id))) co_return;

    SetAutocomplete(matches);
}

bool EditControl::IsLatestId(unsigned id) 
{ 
 return id == m_latestId.load(std::memory_order_relaxed);
} 

The background worker periodically checks whether its work has been discarded and abandons its efforts if so.

std::expected - Monadic Extensions -- Bartlomiej Filipek

BartlomiejFilipek-monadic.pngThe new std::expected feature from C++23 not only offers a robust error-handling mechanism but also introduces functional programming techniques like chaining operations with and_then, transforming results with transform, and managing errors using or_else and transform_error. This article explores these features, demonstrating how they can streamline your code by reducing redundant error checks while elegantly managing success and error states. Stay tuned as we dive into practical examples and see how these techniques are applied in real-world projects.

std::expected - Monadic Extensions

by Bartlomiej Filipek

From the article:

std::expected from C++23 not only serves as an error-handling mechanism but also introduces functional programming paradigms into the language. In this blog post, we’ll have a look at functional/monadic extensions of std::expected, which allow us to chain operations elegantly, handling errors at the same time. The techniques are very similar to std::optional extensions - see How to Use Monadic Operations for `std::optional` in C++23 - C++ Stories.

Here’s a brief overview of these functional capabilities:

and_then()
 
The and_then member function enables chaining operations that might produce a std::expected object. It’s invoked when the std::expected object holds a value and allows for seamless operation chaining without manual error checking after each step.
 

Adding State to the Update Notification Pattern, Part 5 -- Raymond Chen

RaymondChen_5in-150x150.jpgManaging stateful notifications is challenging when multiple requests arrive, and the goal is to only notify about the latest one. In the EditControl class, we use a counter to track the most recent request, updating it on the UI thread to ensure accurate ordering and prevent stale data from being processed. This approach works but is inefficient due to redundant calculations. Next time, we'll refine this strategy for greater efficiency.

Adding State to the Update Notification Pattern, Part 5 

by Raymond Chen

From the article:

We’ve been looking at the problem of a stateful but coalescing update notification, where multiple requests for work can arrive, and your only requirement is that you send a notification for the last one.

This time, we’ll apply the trick of using a counter to record who is doing the work on behalf of the most recent change. Here’s our first attempt:

 
class EditControl
{
    ⟦ ... existing class members ... ⟧

    unsigned m_latestId;
};

winrt::fire_and_forget
EditControl::TextChanged(std::string text)
{
    auto lifetime = get_strong();

    co_await winrt::resume_background();

    auto id = ++m_latestId;

    std::vector<std::string> matches;
    for (auto&& candidate : FindCandidates(text)) {
        if (candidate.Verify()) {
            matches.push_back(candidate.Text());
        }
    }

    co_await winrt::resume_foreground(Dispatcher());

    if (id != m_latestId) co_return;

    SetAutocomplete(matches);
}