Skip to content

Instantly share code, notes, and snippets.

View g-h-c's full-sized avatar

Gerardo Hernandez g-h-c

View GitHub Profile
@s9w
s9w / gist:ad9b1dd1ea6fb17e956559c8b352e246
Last active June 22, 2024 13:35
Potential issue with C++20's initialization change

Potential issue with C++20's initialization change

C++20 takes yet another swing at its infamous initialization rules. The players involved this time are Aggregate initialization (type a{1, 2, 3}) and direct initialization (type a(1, 2, 3)). A common pitfall with aggregate init is:

std::vector<int> vec0(5, 9); // 9, 9, 9, 9, 9
std::vector<int> vec1{5, 9}; // 5, 9

So if you don't know what you're doing, {} is potentially dangerous to use with types that might have both "real" constructors and such with std::initializer_list. If you had your head in the sand for 10 11 years and always used () then you never were in danger.

@shafik
shafik / WhatIsStrictAliasingAndWhyDoWeCare.md
Last active November 8, 2024 20:02
What is Strict Aliasing and Why do we Care?

What is the Strict Aliasing Rule and Why do we care?

(OR Type Punning, Undefined Behavior and Alignment, Oh My!)

What is strict aliasing? First we will describe what is aliasing and then we can learn what being strict about it means.

In C and C++ aliasing has to do with what expression types we are allowed to access stored values through. In both C and C++ the standard specifies which expression types are allowed to alias which types. The compiler and optimizer are allowed to assume we follow the aliasing rules strictly, hence the term strict aliasing rule. If we attempt to access a value using a type not allowed it is classified as undefined behavior(UB). Once we have undefined behavior all bets are off, the results of our program are no longer reliable.

Unfortunately with strict aliasing violations, we will often obtain the results we expect, leaving the possibility the a future version of a compiler with a new optimization will break code we th