`struct Foo f;` and `struct Foo f{};` are very different

Compare the following two programs, and can you predict what the outputs would be for each? // program #1 struct Foo { int x; }; void stack() { int x = 3; } void bar() { struct Foo foo{}; cout << foo.x << endl; } int main() { stack(); bar(); return 0; } // program #2 struct Foo { int x; }; void stack(…

When would someone use std::enable_shared_from_this

std::enable_shared_from_this [https://en.cppreference.com/w/cpp/memory/enable_shared_from_this] allows a class to have a valid shared_ptr of this. Simply adding a member function that returns shared_ptr(this) is susceptible to double-free. But when would you use such a feature?…

Build `folly::coro` with GCC

You have heard about Coroutine in C++, and you want to use it. There're two coroutine implementations that are considered most mature - cppcoro and folly::coro. They are written by the same guy - Lewis Baker. He's brilliant, and you shoud watch his cppcon talk on structured concurrency [https:…

Why you don't need virtual base destructor with smart pointers

struct Foo { // virtual ~Foo() {}; int a; }; struct Bar : public Foo { ~Bar() {std::cout << "bar dtor" << std::endl;}; }; int main() { std::shared_ptr f = std::make_shared(); //Foo* f = new Bar(); return 0; } In this example, the shared_ptr version would work as you expect. The raw pointer version…

SeqLock

Sequential lock is a common technique used to protect data that's frequently read and rarely updated. Writers are required to take exclusive lock to mutate the data. Reads are effectively lock free and optimistic. The data protected by a SeqLock usually needs to be trivially_copy_constructible [https://en.cppreference.…

`folly::Indestructible`

folly::Indestructible [https://github.com/facebook/folly/blob/master/folly/Indestructible.h] is a class template that makes a static variable well, indestructible. Notice that it's meant for static variables in the Meyers Singleton pattern. If it's for heap allocated memory, it would just be called memory leak instead…

C++ Map Lookup Memoization

Memoization is an old technique. It's basically caching outputs for giving inputs (usually in a map). But a map lookup itself is not free. How can we memoize map lookups? I learned from my coworker this nifty trick recently. Let's say we have a map (e.g. std::unordered_map<…

C++ Type Erasure and `std::function`

You have heard about Type Erasure of C++. You probably know std::function is a classic usage of the pattern. But what is Type Erasure in C++? It's effectively trying to achieve Duck Typing, which is common in languages like Python. # Notice that there's no relationship between Bar1 or Bar2…