Articles & Books

Noisy: The Class You Wrote a Hundred Times -- Vincent Zalzal

OXUJNJk0_400x400.jpgYou have probably written a class that prints a message in all its special member functions. And like me, you probably wrote it multiple times. I decided to write it well once and for all, and share it.

Noisy: The Class You Wrote a Hundred Times

by Vincent Zalzal

From the article:

Recently, I was writing some code involving structured bindings and I was unsure whether it would incur unintended copy or move operations. As usual, when I am in this situation, I open up Compiler Explorer and test it. For the nth time, I ended up coding a class like this one:

struct S { 
S() { std::cout << "ctor\n"; } 
~S() { std::cout << "dtor\n"; } 
// ... and so on with copy and move operations 
}

I don’t know how many times I wrote this class! I thought maybe it was time I write it well, once and for all, and then reuse it when I need it. And then, I thought that I am probably not the only one having written that class over and over again, am I? Maybe this could be useful to others.

The Performance Impact of C++'s `final` Keyword -- Benjamin Summerton

book2_final_scene.pngIf you're writing C++, there's a good reason (maybe...) as to why you are. And probably, that reason is performance. So often when reading about the language you'll find all sorts of "performance tips and tricks" or "do this instead because it's more efficient". Sometimes you get a good explanation as to why you should. But more often than not, you won't find any hard numbers to back up that claim. I recently found a peculiar one, the final keyword.

The Performance Impact of C++'s `final` Keyword

by Benjamin Summerton

From the article:

Multiple blog posts claim that it can improve performance(sorry for linking a Medium article). It almost seems like it's almost free, and for a very measly change. After reading you'll notice something interesting: no one posted any metrics. Zero. Nada. Zilch. It essentially is "just trust me bro." Claims of performance improvements aren't worth salt unless you have the numbers to back it up. You also need to be able to reproduce the results. I've been guilty of this in the past (see a PR for Godot I made).

Being a good little engineer with a high performance C++ pet project, I really wanted to validate this claim.

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

RaymondChen_5in-150x150.jpgIn our previous discussion, we explored the intricacies of stateful but coalescing update notifications, shedding light on the pivotal role of the UI thread in implicit serialization. However, what if this luxury of implicit synchronization is absent? Delving into an alternate version of our solution, we confront the looming specter of race conditions and the necessity for meticulous thread management to ensure seamless operation. Join us as we navigate the complexities of thread synchronization and embark on a quest to refine our approach to asynchronous work handling.  

Adding State to the Update Notification Pattern, Part 4

by Raymond Chen

From the article:

Last time, we developed a stateful but coalescing update notification, and we noted that the UI thread was doing a lot of heavy lifting. What if you don’t have a UI thread to do implicit serialization for you?

If there were no resume_foreground(Dispatcher()), we would have a race if a Text­Changed occurs after the worker has decided to exit, but before it has had a chance to mark itself as not busy. Here’s an alternate version that demonstrates the race.

Trip Report: Winter ISO C++ Meeting in Tokyo, Japan -- David Sankel

tokyoreport.pngAnother meeting, another slew of potential changes to standard C++. In this recap, I’ll summarize the working draft’s most significant changes, spotlight my favorite proposal at the meeting, Member customization points for Senders and Receivers, and discuss a handful of notable developments.

Trip Report: Winter ISO C++ Meeting in Tokyo, Japan

by David Sankel

From the article:

What’s new in the draft standard?

This snippet summarizes the notable changes:


	// wg21.link/p2573r2

	void newapi();

	void oldapi() = delete(“oldapi() is outdated, use newapi() instead”);

	

	void f() {

	    std::println(); // Shorthand for ‘std::println(“”)’. wg21.link/p3142r0

	

	    // Paths can be printed/formatted now. wg21.link/p2845r8

	    std::println(“Here’s a path: {}”,

	                 std::filesystem::path(“/stlab/chains”));

	

	    std::vector<int> x{1, 2, 3};

	    std::array<int,3> y{4, 5, 6};

	

	    // Outputs 1, 2, 3, 4, 5, and 6 separated by newlines.

	    for( auto i : std::views::concat(x, y) ) // concat is new from

	        std::cout << i << std::endl;         // wg21.link/p2542r8

	}

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

RaymondChen_5in-150x150.jpgIn our continued exploration of efficient stateful update notifications, we delve into optimizing our existing solution to mitigate unnecessary background work. By introducing periodic checks for pending text and leveraging mutex protection, we aim to streamline the process and enhance performance. However, as we unravel these optimizations, we confront the complexities of managing thread safety and delve into the intricacies of background thread synchronization.

Adding State to the Update Notification Pattern, Part 3

by Raymond Chen

From the article:

Last time, we developed a stateful but coalescing update notification, and we noted that the code does a lot of unnecessary work because the worker thread calculates all the matches, even if the work has been superseded by another request.

We can add an optimization to abandon the background work if it notices that its efforts are going to waste: Periodically check whether there is any pending text. This will cost us a mutex, however, to protect access to m_pendingText from multiple threads.

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

RaymondChen_5in-150x150.jpg

In the realm of asynchronous programming, managing stateful update notifications presents a daunting challenge. In our ongoing exploration, we scrutinize a solution that aims to address this challenge by seamlessly handling multiple requests for work while ensuring that only the last one triggers a notification. However, beneath the surface of this endeavor lies a tangle of legal intricacies and logical pitfalls, urging us to dissect, refine, and ultimately fortify our approach.

Adding State to the Update Notification Pattern, Part 2

by Raymond Chen

From the article:

Last time, we started looking at solving 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. Any time a new request for work arrives, it replaces the existing one.

One attempt to fix this is to check if the work is already in progress, and if so, then hand off the new query to the existing worker. We are using winrt::fire_and_forget, which fails fast on any unhandled exception. This saves us from having to worry about recovering from exceptions. (At least for now.)

User-Defined Formatting in std::format -- Spencer Collyer

logo.pngstd::format allows us to format values quickly and safely. Spencer Collyer demonstrates how to provide formatting for a simple user-defined class.

User-Defined Formatting in std::format

by Spencer Collyer

From the article:

Since my previous article was first published, based on the draft C++20 standard, the paper [P2216] was published which changes the interface of the formatformat_toformat_to_n, and formatted_size functions. They no longer take a std::string_view as the format string, but instead a std::format_string (or, for the wide-character overloads std::wformat_string). This forces the format string to be a constant at compile time. This has the major advantage that compile time checks can be carried out to ensure it is valid.

The interfaces of the equivalent functions prefixed with v (e.g. vformat) has not changed and they can still take runtime-defined format specs.

One effect of this is that if you need to determine the format spec at runtime then you have to use the v-prefixed functions and pass the arguments as an argument pack created with make_format_args or make_wformat_args. This will impact you if, for instance, you want to make your program available in multiple languages, where you would read the format spec from some kind of localization database.

Another effect is on error reporting in the functions that parse the format spec. We will deal with this when describing the parse function of the formatter classes described in this article.

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

RaymondChen_5in-150x150.jpgIn software development, handling notifications efficiently is pivotal, particularly in user interface scenarios. While traditional notification patterns inform handlers of changes, they often lack crucial state information. In this article, we explore the intricacies of managing stateful updates within the context of C++/WinRT, addressing challenges such as race conditions and ensuring that notification handlers operate on the most recent data for optimal user experience.

Adding State to the Update Notification Pattern, Part 1

by Raymond Chen

From the article:

Some time ago, we looked at the update notification pattern, but in those cases, the notification carried no state.

Consider the case where you want to call a notification handler, and the handler also receives a copy of data derived from the most recent state, rather than just being called to be told that something changed and forcing them to figure out what changed.

For example, suppose you want to add autocomplete to an edit control, but calculating the autocomplete results is potentially slow, so you want to do it in the background. But while you are calculating the autocomplete results, the user might type into the edit control, and you want the final autocomplete results to reflect the most recent edit in the edit control, rather than any results from what the edit control used to contain at some point in the past.

Embedding (and Extracting) DLLs into EXEs as Binary Resources -- Giovanni Dicanio

Windows EXE files can contain resources, including binary resources. In particular, you can embedd one or more DLLs into an EXE, and then extract them at run-time. Let's learn more about that in the following article:

Embedding (and Extracting) Binary Files like DLLs into an EXE as Resources

by Giovanni Dicanio

From the article:

A Windows .EXE executable file can contain binary resources, which are basically arbitrary binary data embedded in the file.

In particular, it’s possible to embed one or more DLLs as binary resources into an EXE. In this article, I’ll first show you how to embed a DLL as a binary resource into an EXE using the Visual Studio IDE; then, you’ll learn how to access that binary resource data using proper Windows API calls.

(...)

Once you have embedded a binary resource, like a DLL, into your EXE, you can access the resource’s binary data using some specific Windows APIs. (...)

The above “API dance” can be translated into the following C++ code: (...)

I uploaded on GitHub a C++ demo code that extracts a DLL embedded as a resource in the EXE, and, for testing purposes, invokes a function exported from the extracted DLL.

Looking for Pointers: The C++ Memory Safety Debate -- John Farrier

From the White House to the NSA to Bjarne Stroustrup has an opinion on C++ and Memory Safety.  Let's examine this from a historical context and see where this debate may lead.

Looking for Pointers: The C++ Memory Safety Debate

by John Farrier

From the article:

The dialogue around C++ and memory safety has intensified following recent evaluations by authoritative bodies. The White House’s Office of the National Cyber Director issued a compelling call for a pivot toward memory-safe programming languages. This stance is predicated on a history of cyber vulnerabilities linked to memory safety issues, influencing national security and the broader digital ecosystem’s integrity.

This debate takes place against a backdrop of historical precedence, technological evolution, and a reevaluation of programming language safety standards, underscoring the need for a nuanced understanding of memory safety within the context of C++.