Hacker News new | ask | show | jobs
by bingo3131 802 days ago
A post about an obscure C++ feature on Hacker News? Comments are going to be a dumpster-fire as usual.

https://en.cppreference.com/w/cpp/utility/launder

"template <class T> [[nodiscard]] constexpr T* launder (T* p) noexcept;

Provenance fence with respect to p. Returns a pointer to the same memory that p points to, but where the referent object is assumed to have a distinct lifetime and dynamic type."

It's a function for the compiler for low-level memory management and lifetime management code (i.e. code almost no C++ "end-user" writes) to turn off compile-time tracking and optimisations that might not be correct. Typically only used if you're starting the lifetime of one object over or inside another. Essentially, when you want the compiler to be dumb you launder the pointer to make the compiler intentionally forget the complex compile-time state tracking that compilers do and make the compiler pretend that pointer is actually a brand new object it knew nothing about.

Someone brought up the volatile keyword: volatile is for turning off compiler assumptions about what a value might be at run-time. For example, if you read from a regular int twice in a row with no write in between, then the compiler would likely remove the second read and reuse the first value (better code-gen) as it knows the value could not have changed. The volatile keyword is how you tell the compiler that it cannot reliably observe all changes to the variable so every read must be performed (same for writes).

launder and volatile are similar in so much that they exist to tell the compiler not to make assumptions about the values/objects, but that's about it. They are not interchangeable.

But let's all pretend this function is something everyone using C++ needs to use to farm some internet points.