C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fwd: Use of volatile as function argument should not be deprecated.

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Fri, 10 Jun 2022 11:06:01 -0400
On Fri, Jun 10, 2022 at 5:34 AM Marcin Jaczewski via Std-Proposals <
std-proposals_at_[hidden]> 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

Received on 2022-06-10 15:06:13