←back to thread

In Defense of C++

(dayvster.com)
185 points todsacerdoti | 2 comments | | HN request time: 0s | source
Show context
monkeyelite ◴[] No.45270587[source]
The complexity argument is just not true. You do have to know this stuff in c++, you run into it all the time.

I wish I didn’t have to know about std::launder but I do

replies(2): >>45270919 #>>45271366 #
jandrewrogers ◴[] No.45271366[source]
You need something like std::launder in any systems language for certain situations, it isn’t a C++ artifact.

Before C++ added it we relied on undefined behavior that the compilers agreed to interpret in the necessary way if and only if you made the right incantations. I’ve seen bugs in the wild because developers got the incantations wrong. std::launder makes it explicit.

For the broader audience because I see a lot of code that gets this wrong, std::launder does not generate code. It is a compiler barrier that blocks constant folding optimizations of specific in-memory constants at the point of invocation. It tells the compiler that the constant it believes lives at a memory address has been modified by an external process. In a C++ context, these are typically restricted to variables labeled ‘const’.

This mostly only occurs in a way that confuses the compiler if you are doing direct I/O into the process address space. Unless you are a low-level systems developer it is unlikely to affect you.

replies(1): >>45271885 #
monkeyelite ◴[] No.45271885[source]
Do you see all the concepts you had to describe here?

> Unless you are a low-level systems developer it is unlikely to affect you.

Making new data structure is common. Serializing classes into buffers is common.

replies(2): >>45272201 #>>45272912 #
1. jandrewrogers ◴[] No.45272201{3}[source]
If you are doing something equivalent to placement new on top of existing objects, the compiler often sees that. If that is your case you can avoid it in most cases. That is not what std::launder is for. It is for an exotic case.

std::launder is a tool for object instances that magically appear where other object instances previously existed but are not visible to the compiler. The typical case is some kind of DMA like direct I/O. The compiler can’t see this at compile time and therefore assumes it can’t happen. std::launder informs the compiler that some things it believes to be constant are no longer true and it needs to update its priors.

replies(1): >>45276682 #
2. monkeyelite ◴[] No.45276682[source]
With placement new you need to hold on to the pointer. If you need to get an object back out of a buffer you need launder.

Std::vector needs launder.