Showing posts with label cppcon_2025. Show all posts
Showing posts with label cppcon_2025. Show all posts

Jan 14, 2026

[C++] Cache-friendly

 Just always having int as default if usage is under contract.



Reference:
Object Lifetimes reading minute
alignas(int) unsigned char buffer[sizeof(int)]; // used for provenance contract.

One byte types:

Benchmark shows
char8_t is faster due to optimizer.
this is that a pointer of char, unsigned char, or std::byte type can point to anywhere, thus
data.size() could potentially being modified inside the loop, thus accessing data.size() is necessary.
As for char8_t has no this privilege, thus data.size() is fixed and stored inside a register.

The Problem: "Type Aliasing" & The Strict Aliasing Rule
In C++, the compiler assumes that two pointers of different types do not point to the same memory location. This allows for massive optimizations.

However, there is a historical exception to this rule: char types (char, signed char, unsigned char) and std::byte are allowed to alias anything.
Thus:
For char, unsigned char, and std::byte:
The compiler looks at data[i] = ... and thinks: "Uh oh. Writing to this byte might technically be overwriting the memory where the std::vector object itself keeps its internal size tracker!"
Because a char* can point anywhere, the compiler is forced to be incredibly cautious. It re-reads data.size() from memory on every single iteration of the loop just in case the last write accidentally changed it. This slows things down.

For char8_t:
When char8_t was introduced in C++20 for UTF-8 string data, the committee decided not to give it this "alias anything" superpower. It obeys strict aliasing.
The compiler looks at the loop and thinks: "Writing to a char8_t array cannot possibly change the std::vector's internal size variables because they are different types."




fix: old trick, store the data.size() inside the register ourselves.

or just:


Bitfields is good for saving memory but accessing them are slow (bitmask other values).
also, under meta-programming, type inference of those bitfields type has to be casted.


Reference:

When choosing a container type to use, consider:


L2 cache is used for data and instructions.
i.e. how we code matters the speed, even the results are the same.
e.g.
slower, due to branch and if branch succeed, instructions are replaced in the cache.

faster, due to branch rarely happen, and REPEAT64 has much more instruction than simple count+=d

Summary


Reference:

Always start with DoD; focus on algorithm.

DoD is more packed with data layout, good for caching.

SoA
Reference:
Align with the cache line to avoid false sharing

CS 101, keep false sharing affect in mind.


All-in-all summary


Avoid long branches:

// BAD
void process_data(Data* d) {
    if (!d) {
        // LONG BRANCH / COLD CODE
        // Imagine 100 lines of logging, stack tracing, 
        // and complex error recovery logic here.
        log_error("Null pointer detected...");
        cleanup_subsystems();
        notify_admin_via_snmp();
        throw std::runtime_code("Fatal Error");
    }

    // This "hot" code is now physically far away from the 'if' 
    // check in the compiled binary.
    d->value += 42; 
    d->status = Ready;
}

// Better, avoid I-Cache miss

// Move cold logic to a non-inline function
[[noreturn]] void handle_fatal_error() {
    log_error("Null pointer detected...");
    cleanup_subsystems();
    notify_admin_via_snmp();
    throw std::runtime_code("Fatal Error");
}

void process_data_optimized(Data* d) {
    // C++20 [[likely]]/[[unlikely]] attributes guide the compiler
    if (!d) [[unlikely]] {
        handle_fatal_error(); // A jump to a far-away location happens ONLY on error
    }

    // This code is now physically adjacent to the 'if' check
    d->value += 42; 
    d->status = Ready;
}




Dec 15, 2025

[C++] [CppCon 2025] Implement the C++ Standard Library minute

Reference:

Implement the C++ Standard Library: Design, Optimisations, Testing while Implementing Libc++
[C++] Object Lifetimes reading minute

1)

1) tail padding.
2) if type is empty, it does not acquire address.

e.g.
struct Foo {
  int a; // 4
  char c; // 1 
  bool b; // 1
  // +2
};

enum class ErrCode : int {
 E1, E2, E3,
};

template<typename Val, Err>
struct Expected {
  union U {
  	[[no_unique_address]] Val val_;
	[[no_unique_address]] Err err_;
  };
  [[no_unique_address]] U value_;
  bool has_value_; 
};
Without `no_unique_address`, no tail padding,
sizeof(Expected<Foo, ErrCode>) == 12

With `no_unique_address`, 
bool has_value_;
can sneak into
U if U is of type Foo, `has_value_` would occupy Foo's tail padding,
thus:
sizeof(Expected<Foo, ErrCode>) == 8


2)

template<typename Val, Err>
struct Expected {
  union U {
  	[[no_unique_address]] Val val_;
	[[no_unique_address]] Err err_;
  };
  [[no_unique_address]] U value_;
  bool has_value_; 
  
  Expected(const Expected& other) :
  	has_value{other.has_value} {
	 if (has_value_) {
	 	std::construct_at(std::addressof(value_.val_), other.value_.val_);
	 } else {
	 	std::construct_at(std::addressof(value_.err_), other.value_.err_);
	 }
	}
};

Expected e1 = {Foo{}, true};
Expected e2 = e1;
assert(e2.has_value_); // Failed.
Why failed? Due to std::construct_at construct the value_ union's val_ and
zero out the padding, which has_value_ resides in due to `no_unique_address`.

Take away:

Don't mix no_unique_address with manual lifetime management
(union, construct_at, placement-new, std::bit_cast, std::start_lifetime_as, std::start_lifetime_as_array).


3)

Reference:
Segmented Iterators and Hierarchical Algorithms - Matthew H. Austern
https://lafstern.org/matt/segmented.pdf
Which is faster?
std::deque<int> d = ...

// 1
for (int& i : d) {
    i = std::clamp(i, 200, 500);
}

// 2 Faster due to using Segmented Iterators
std::ranges::for_each(d, [](int& i) {
    i = std::clamp(i, 200, 500);
});

Segmented Iterators:

template <class T> struct seg_array_iter
{
    // Local Iterator: position within the current segment (e.g., a vector<T>::iterator)
    vector<T>::iterator cur;
    
    // Segment Iterator: position among the segments (e.g., a vector<vector<T>*>::iterator)
    vector<vector<T>*>::iterator node;

    T& operator*() const { return *cur; }

    seg_array_iter& operator++() {
        // Standard increment: move to the next element in the current segment
        if (++cur == (**node).end()) {
            // End of segment reached: move to the next segment
            ++node;
            // Set the local iterator (cur) to the beginning of the new segment
            // or 0 (a null pointer equivalent for iterators) if it's the end.
            cur = *node ? (**node).begin() : 0;
        }
        return *this;
    }
    // ... other iterator operations like operator==, operator!=, etc.
};

template <class Iter, class T>
inline void fill (Iter first, Iter last, const T& x)
{
    typedef segmented_iterator_traits<Iter> Traits;
    
    // Dispatch call: The compiler chooses the segmented or nonsegmented helper 
    // based on the type of Traits::is_segmented_iterator (true_type or false_type).
    fill(first, last, x,
         typename Traits::is_segmented_iterator()); 
}

template <class SegIter, class T>
void fill (SegIter first, SegIter last, const T& x, true_type)
{
    typedef segmented_iterator_traits<SegIter> traits;

    // Decompose the full segmented iterators into segment and local iterators
    typename traits::segment_iterator sfirst = traits::segment (first);
    typename traits::segment_iterator slast = traits::segment (last);

    if (sfirst == slast) {
        // Case 1: Start and end are in the same segment. Use one local fill.
        fill(traits::local (first), traits::local (last), x);
    } else {
        // Case 2: Fill the *rest* of the starting segment
        fill(traits::local (first), traits::end(sfirst), x);

        // Case 3: Loop through all *middle* segments, filling them completely
        for (++sfirst; sfirst != slast; ++sfirst)
            fill(traits::begin(sfirst), traits::end(sfirst), x);

        // Case 4: Fill the *start* of the ending segment (sfirst now equals slast)
        fill(traits::begin(sfirst), traits::local (last), x);
    }
} 

Take away:

  • Use the most precise API for what you're trying to achieve.
    • insert_range instead of insert in a loop. (O(n) vs. N * log(M) )
    • use sorted_unique if the inputs are already sorted.
  • Use library facilities (e.g. views::zip) to benefit from concept-based optimizations.


4)

compiler flag
-Xclang -verify used for static_asserts
e.g.
clang++ -Xclang -verify -fsyntax-only test_integer_only.cpp

#include <type_traits>

template <typename T>
void strict_int_check() {
    static_assert(std::is_integral<T>::value, "Type must be an integer!");
}

void test() {
    // This line is valid, so no comment needed.
    strict_int_check<int>();

    // We WANT this line to fail. 
    // Without -verify, this breaks the build.
    // With -verify, Clang checks if the error matches the regex in {{...}}.
    strict_int_check<double>(); // expected-error {{Type must be an integer!}}
}

Sep 23, 2025

[C++][Cppcon 2025] Concept-based Generic Programming - Bjarne Stroustrup

Reference:
Concept-based Generic Programming - Bjarne Stroustrup - CppCon 2025

Concepts are functions

OOP

  • Focused on defining type of objects, often in class hierarchies
  • Applies to one object at a time
  • Relies on name equivalence
  • Run-time selection among an open set of types
  • Inlining is difficult (typically impossible)
  • Defining an interface requires precisely specifying types
    requires significant foresight, conceptually and in technical details.

GP

  •  Focused on a functions' requirements on its arguments
  •  Often involving relationships among multiple arguments
  •  Relies on use patterns (a generalization of structural equivalence)
  •  Compile-time selection among types in scope
  •  Inlining is easy
  •  Doesn't offer interfaces in the ABI sense
        Use OOP for that

Concepts can be partial constraints

We can't always get first shot perfect. Needs several iterations.


Concept can take value arguments

not just type arguments(same as template, i.e. non-type arguments)


Concepts are not just for template arguments


Concept type matching


Definition checking





e.g.
consteval bool is_power_of_two(int n) {
  if (n == 0) return false;
  while ((n&1) == 0) {
    n >>= 1;
  }
  return (n==1);
}


template<int S> concept buffer_space = (1024 <= S) && is_power_of_two(S);

template<typename T, int S>
  requires buffer_space<S>
struct Buffer {
  T buf[S];
};


void test0() {
  Buffer<char, 100> b1; // error, too small.
  Buffer<char, 10000> b2; // error, not binary
  Buffer<int, 2048> b3; // ok
}