On Fri, Jun 10, 2022 at 5:34 AM Marcin Jaczewski via Std-Proposals <std-proposals@lists.isocpp.org> wrote:
> >> >
> >> >     void foo(int *p) {
> >> >         if (!p) { printf("null pointer\n"); }
> >> >         volatile bool b = false;
> >> >         if (b) { abort(); }
> >> >         *p = 0;
> >> >     }
[...]
Why not simply name this attribute `[[do_not_optimize]]`?

Google Benchmark already has this, and I wouldn't be surprised if more than one corporate codebase also has it. It's a pure library feature, implementable in plain old standard C++.

    // In another .cpp file:
    void escape(void*) {}

    // In the header file:
    extern void escape(void*);
    template<class T> void DoNotOptimize(T&& t) { escape(&t); }

    void foo(int *p) {
        if (!p) { printf("null pointer\n"); }
        DoNotOptimize(p);
        *p = 0;
    }

The compiler can see that `escape(&p)` is called, but it doesn't know at compile time whether `escape` might throw or terminate, so it can't assume that the line `*p = 0` will necessarily be reached (so it can't hoist that line upward and it can't remove the null-check).

–Arthur