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

Your attention is invited to the fifth 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 5 of 11

by Dmitry Sviridkin

From the article:

However, all this fuss with removing and adding const anywhere in the code eliminates this set of optimizations. So, a repeated access by a constant reference to the same data member or member function doesn't need to be cached at all. Note. It's worth mentioning that programmers have unrealistic expectations about the compiler optimizing code when they add more const. Here's a good note on the topic: "Why const Doesn't Make C Code Faster".

CppCon 2024 Contracts for C++ -- Timur Doumler

Registration is now open for CppCon 2024! The conference starts on September 15 and will be held in person in Aurora, CO. To whet your appetite for this year’s conference, we’re posting some upcoming talks that you will be able to attend this year. Here’s another CppCon future talk we hope you will enjoy – and register today for CppCon 2024!

Contracts for C++

Wednesday, September 18 14:00 - 15:00 MDT

by Timur Doumler

Summary of the talk:

Design by Contract is a very effective approach for writing safer, more correct programs. It has been successfully implemented in programming languages like Eiffel and Ada. Attempts to add a Contracts facility to C++ have a long and storied history spanning two decades. Since the last attempt to standardise Contracts (for the C++20 Standard) has failed, SG21 — the Contracts Study Group on the C++ Standard Committee – has been working on a new design, the so-called Contracts MVP, which is now essentially feature-complete and on track to make it into the upcoming C++26 Standard.

In this talk, we present the current design of the Contracts MVP targeting C++26. We discuss preconditions, postconditions, assertions, contract-violation handling and much more. We consider how the Contracts MVP provides a superior replacement for custom assertion macros and, when used correctly, can significantly improve the safety and correctness of your code.


Timur Doumler is the co-host of CppCast and an active member of the ISO C++ standard committee, where he is currently co-chair of SG21, the Contracts study group. Timur started his journey into C++ in computational astrophysics, where he was working on cosmological simulations. He then moved into the audio and music technology industry, where he has been working for over a decade and co-founded the music tech startup Cradle. In the past, Timur also worked for JetBrains, first as a developer on CLion's C++ parser and later as a Developer Advocate for C++ developer tools. Currently, Timur lives in Finland, where he is organising the monthly C++ Helsinki meetup. Timur is passionate about clean code, good tools, low latency, and the evolution of the C++ language.

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

In previous posts, we've explored relocation, trivial relocation, and their use in optimizing data structures like vector-like containers. We've also examined how trivial relocation relates to move assignments, enabling further optimization of operations like swaps and algorithms such as std::sort and std::rotate.

Qt and Trivial Relocation (Part 5)

by Giuseppe D'Angelo

From the article:

Is trivial relocation allowed in Standard C++?

That’s probably a question we should have asked as soon as we started this journey. Of course, the answer is no, it is not allowed!

Remember how trivial relocation works: we use memcpy a source object(‘s representation) into some storage, and claim that operation realizes the equivalent of move-constructing the source into that storage, plus destroying the source.

The problem is that one can’t just put data into some storage and pretend that an object exists in there. This is only allowed for a specific set of types, such as trivially copyable types. (Note that if a type is trivially copyable, then Qt automatically considers it trivially relocatable.)

However, as we have discussed, many interesting types (QStringstd::vectorstd::unique_ptr, …) are not trivially copyable, but they would still benefit from trivial relocatability.

CppCon 2024 Data Structures That Make Video Games Go Round -- Al-Afiq Yeong

Registration is now open for CppCon 2024! The conference starts on September 15 and will be held in person in Aurora, CO. To whet your appetite for this year’s conference, we’re posting some upcoming talks that you will be able to attend this year. Here’s another CppCon future talk we hope you will enjoy – and register today for CppCon 2024!

Data Structures That Make Video Games Go Round

Friday, September 20 14:45 - 15:45 MDT

by Al-Afiq Yeong

Summary of the talk:

Modern video games are complex beasts that contains multiple systems interacting with one another storing, transferring and processing large sets of data in real time. While some data structures from the standard library such as the std::vector gets you by 90% of the time you need to store and process data, there will be the occasional 10% that requires a unique take.

This presentation aims to discuss the unique data structures that are commonly used in video games / game engines that caters to the occasional 10%. We will go over several systems outlining their requirements, constraints and present custom data structures that gets the job done.


Al-Afiq Yeong is a Software Engineer currently working in the Engine team at Criterion. His day to day involves performance monitoring games, making sure memory gets managed efficiently and developing new technologies that will empower future games developed with Frostbite. Prior to games, he was a full stack developer maintaining and building web apps in the service, nuclear and finance industry. Outside work, he spends most of his time writing his own rendering engine while trying to avoid the allure of the games sitting in his Steam library.

Understanding the inner workings of C++ smart pointers -- Andreas Fertig

me.pngPreviously, we explored a basic implementation of unique_ptr in "Understanding the Inner Workings of C++ Smart Pointers - The unique_ptr." Now, let's enhance that model by incorporating a custom deleter, similar to what the Standard Library provides.

Understanding the Inner Workings of C++ Smart Pointers - The Unique_ptr with Custom Deleter

by Andreas Fertig

From the article:

Let's first establish why somebody would want a custom deleter.

One example is that the object was allocated via a local heap, and such must be returned by calling the corresponding deallocation function.

Another example is fopen. This function returns a FILE* object that you are supposed to delete by calling fclose. A classic job for a unique pointer. But you cannot call delete on the FILE pointer.

Here are two examples of using a unique_ptr with a custom deleter.

void MyDeleter(Object* ptr)
{
  delete ptr;
}

unique_ptr<Object> alfred{new Object{}};
static_assert(sizeof(alfred) == sizeof(void*));

unique_ptr<Object, decltype(MyDeleter)> robin{new Object{}, &MyDeleter};
static_assert(sizeof(robin) == sizeof(void*) * 2);
 
Oh yes, the first object, alfred, doesn't provide a custom deleter. Only robin does. Behind the curtains, both do. Let's look at a modified unique_ptr implementation that handles the custom deleter case.

CppCon 2024 Embracing an Adversarial Mindset for C++ Security -- Amanda Rousseau

Registration is now open for CppCon 2024! The conference starts on September 15 and will be held in person in Aurora, CO. To whet your appetite for this year’s conference, we’re posting some upcoming talks that you will be able to attend this year. Here’s another CppCon future talk we hope you will enjoy – and register today for CppCon 2024!

Embracing an Adversarial Mindset for C++ Security

Wednesday, September 18 10:30 - 12:00 MDT

by Amanda Rousseau

Summary of the talk:

In an era where cybersecurity threats are ever-evolving, securing C++ applications has never been more critical. This keynote will explore how adopting an adversarial mindset can empower developers to proactively identify and mitigate vulnerabilities. We will delve into common C++ vulnerabilities, the “Rule of Two” security guidelines, and practical strategies for reducing attack surfaces and defending against attack vectors. Additionally, we will discuss recent trends in vulnerabilities, highlight bug bounty costs, and examine real-world examples of vulnerabilities exploited by threat actors. This talk will provide valuable insights into adopting an adversarial mindset and implementing robust security practices in your C++ projects.


Amanda is an industry expert on malware and understanding ways to be robust against attacks.

Opaque Pointer Pattern in C++ -- Daniel Sieger

sieger-opaquepattern.pngAfter reading this article, you should understand the basics of the opaque pointer pattern and how you can implement it using std::unique_ptr. I also gave some hints on when it is appropriate to use it and when maybe not.

Opaque Pointer Pattern in C++

by Daniel Sieger

From the article:

The basic problem is that C++ class declarations expose private details of the class. Private member functions and data members need to be declared in the header. Here’s an example for illustration:

// Point.h


class Point
{
public:
  Point(float x, float y);
  float x();
  float y();

private:
  float x_;
  float y_;
};

While users of this class don’t have direct access to the private data members x_ and y_, there is still a dependency: If you change the private implementation details of Point, all other compilation units that include Point.h know about the change and need to be re-compiled.

This only gets worse for more complex dependency chains, e.g., when there are dependencies to other classes internal to the module that need to be included. To a certain degree, this can be dealt with by using forward declarations. However, at the end of the day there is an information leak: Private implementation details are leaking to clients. This goes directly against the idea of information hiding.

The opaque pointer pattern helps to deal with this problem.

CppCon 2024 Reflection Is Not Contemplation -- Andrei Alexandrescu

Registration is now open for CppCon 2024! The conference starts on September 15 and will be held in person in Aurora, CO. To whet your appetite for this year’s conference, we’re posting some upcoming talks that you will be able to attend this year. Here’s another CppCon future talk we hope you will enjoy – and register today for CppCon 2024!

Reflection Is Not Contemplation

Friday, September 20 14:45 - 15:45 MDT

by Andrei Alexandrescu

Summary of the talk:

The C++ community has long been interested in reflection, and we have made significant progress in adding core reflection capabilities to the language. While there is emerging clarity on the querying side of reflection—inspecting existing code artifacts programmatically—there is considerably less consensus on the generative aspect: using reflection insights to emit new code. As a result, current proposals showcase a stark contrast between well-polished reflection query capabilities and limited code generation capabilities.

Reifying only the reflection of preexisting code in an Ouroboros manner leads to a curious circularity that hinders the synthesis of new artifacts. This talk provides examples that demonstrate the necessity of generative capabilities in reflection and discusses current and upcoming proposals for generative extensions in C++ reflection.


Andrei Alexandrescu is a Principal Research Scientist at NVIDIA. He wrote three best-selling books on programming (Modern C++ Design, C++ Coding Standards, and The D Programming Language) and numerous articles and papers on wide-ranging topics from programming to language design to Machine Learning to Natural Language Processing to fundamental algorithms. Andrei holds a PhD in Computer Science from the University of Washington and a BSc in Electrical Engineering from University "Politehnica" Bucharest. He is the Vice President of the D Language Foundation.

Enum Class Improvements for C++17, C++20 and C++23 -- Bartlomiej Filipek

Filipek-enumclass.pngThe evolution of the C++ language continues to bring powerful features that enhance code safety, readability, and maintainability. Among these improvements, we got changes and additions to enum class functionalities across C++17, C++20, and C++23. In this blog post, we’ll explore these advancements, focusing on initialization improvements in C++17, the introduction of the using enum keyword in C++20, and the std::to_underlying utility in C++23.

Enum Class Improvements for C++17, C++20 and C++23

by Bartlomiej Filipek

From the article:

Before diving into the enhancements, let’s briefly recap what enum class is. An enum class (scoped enumeration) provides a type-safe way of defining a set of named constants. Unlike traditional (unscoped) enums, enum class does not implicitly convert to integers or other types, preventing accidental misuse. Here’s a basic example:

#include <iostream>

enum class Color {
    Red,
    Green,
    Blue
};

int main() {   
    Color color = Color::Red;

    if (color == Color::Red)
        std::cout << "The color is red.\n";

    color = Color::Blue;

    if (color == Color::Blue)
        std::cout << "The color is blue.\n";

    // std::cout << color; // error, no matching << operator
    // int i = color;      // error: cannot convert
}

CppCon 2024 Gazing Beyond Reflection for C++26 -- Daveed Vandevoorde

Registration is now open for CppCon 2024! The conference starts on September 15 and will be held in person in Aurora, CO. To whet your appetite for this year’s conference, we’re posting some upcoming talks that you will be able to attend this year. Here’s another CppCon future talk we hope you will enjoy – and register today for CppCon 2024!

Gazing Beyond Reflection for C++26

Friday, September 20 16:15 - 18:00 MDT

by Daveed Vandevoorde

Summary of the talk:

In less than a year since its original publication, the WG21 proposal “Reflection for C++26” (P2996) has made good progress towards its titular goal.  From its inception, we intended that design to offer a modest-but-useful set of features with a solid foundation on top of which we will be able to incrementally grow an easy-to-use, rich, and extensible C++ meta-programming framework.  This keynote will review some of the fundamental tools proposed in P2996 and follow up with a vision for some additional capabilities that we’re working on.


David ("Daveed") Vandevoorde is a Belgian computer scientist who lives near Princeton, NJ, USA. He is vice-president of engineering at the Edison Design Group (EDG), where he contributes primarily to the implementation of their C++ compiler front end. He is an active member of the C++ standardization committee where he is primarily active in the core language evolution work. His recent work in that context has primarily been about extending the capabilities of “constexpr evaluation”. Daveed is also one of the five members of the committee’s “direction group”. He is the primary author of the well-regarded “C++ Templates: A Complete Guide” (now available in its second edition).