C++ Logo


Advanced search

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

From: Thiago Macieira <thiago_at_[hidden]>
Date: Wed, 08 Jun 2022 18:08:14 -0700
On Wednesday, 8 June 2022 14:46:58 PDT Ryan P. Nicholl via Std-Proposals
> Hello. I just wanted to point out a usage of volatile that I don't think
> should be deprecated. Namely, the use of volatile on a function argument.

That's a clear one that should be deprecated. For architectures that pass
parameters in the stack, the address is practically arbitrary, is definitely on
the stack, and is usually exclusive to the callee. For architectures that pass
parameters in registers, there's simply no way to have a volatile register.

> This may sound weird but it can be useful to create a parameter like
> 'volatile bool collect_debug_info = false' that gets passed down to
> functions that get called by the function. The function is called with it
> always false so if the function is inlined the compiler will elide all the
> instances of it being checked. Simply editing the variable in the debugger
> can be useful to collect information this way for a specific execution
> without having to do anything more complicated. I would therefore suggest
> this be either 1. un-deprecated, possibly as a defect report for C++20 or
> 2. a new keyword or attribute specifically for values that are intended to
> be changed in a debugger so that it still warns people misusing it for
> threading. I'm also unsure about the value of deprecating += and such, but
> it's definitely understandable.

You're talking about optimisations, which means QoI. If you don't want the
compiler to elide that variable, then please talk to your compiler vendor.
None of your needs are related to the volatileness of said variable. And your
compiler is allowed to remove that volatile variable as you've described under
the "as-if" optimisation rule because it clearly cannot be observed by other
threads of execution or even signal handlers. The only reason you're getting
the behaviour you want is because when compilers see volatile, they usually
shut their brains off and stop optimising well.

volatile variables only make sense if you're doing MMIO or similar
technologies where the acts of reading or writing are, themselves, observable.
Reading of stack, heap and regular global variables is not an observable act.

Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
   Software Architect - Intel DPG Cloud Engineering

Received on 2022-06-09 01:08:20