benchmark icon indicating copy to clipboard operation
benchmark copied to clipboard

[BUG] DoNotOptimize on values with const members again

Open krzikalla opened this issue 7 months ago • 0 comments

Describe the bug This is a follow-up to #764 . That one is closed, but I fail to see a fix there.

#include <benchmark/benchmark.h>

struct X
{
  X() : value{} {}

  const int value;
};

template<class T>
void foo(T&& f)
{
    X x;
    f(x);
}

int main() {
  foo([](const auto& i) { benchmark::DoNotOptimize(i); });
}

Playground (works with any recent gcc version): https://godbolt.org/z/Gz4vTo9ed

If the lambda parameter is declared const auto&: <source>:18:51: warning: '...' is deprecated: The const-ref version of this method can permit undesired compiler optimizations in benchmarks [-Wdeprecated-declarations]

If the lambda parameter is declared auto&: benchmark/benchmark.h:585:3: error: read-only reference 'value' used as 'asm' output

How do I change my code so that DoNotOptimize works reliable and the compiler doesn't warn?

krzikalla avatar Jun 10 '25 12:06 krzikalla