New attributes in C++20

CMP
4 min readJan 28, 2024

In a previous article, I discussed the common programming attributes used in C++ to communicate with the compiler and express intent, such as [[maybe_unused]] and [[fallthrough]]. This article will cover a few more attributes that were introduced in C++20.

Below are the new/updated attributes introduced by the C++20 standard:

  • [[no_unique_address]]: Indicates that a non-static data member doesn’t need a distinct address from all other non-static data members of its class.
  • [[likely]] / [[unlikely]]: Indicates that the compiler should optimize for the case where a path of execution is more or less likely than any other path of execution.
  • [[nodiscard("reason")]]: Expands upon the C++17 [[nodiscard]] attribute, allowing a rationale to be given alongside the compiler warning as to why a value should not be discarded.

Let’s look at each of these in closer detail.

New attribute #1: [[no_unique_address]]

This attribute was added to optimize the memory layout of classes and structs. It tells the compiler that a particular non-static data member doesn’t need a unique memory address from the other non-static data members of its class/struct and therefore can share the same address. Consider the following example:

#include <iostream>

// Regular unique_ptr without [[no_unique_address]]
template<class T, class Deleter = std::default_delete<T>>
class unique_ptr_regular {
public:
~unique_ptr_regular() {…

--

--

CMP

Software engineer specializing in operating systems, navigating the intracicies of the C++ language and systems programming.