Why can a volatile type be constant when returned by constant functions?

The C ++ class has member functions with the following code:

const volatile stats_t& get_stats() const{
        return stats;
    }

      

What could be the reason for using both const and volatile? What exactly does this feature achieve? If the return type is const, doesn't it contradict its purpose using volatile?

+3


source to share


2 answers


const

does not contradict volatile

Marking something as const

means "it won't be changed by this piece of code, it's a constant value / pointer / whatever"



Marking something as volatile

means "do not cache this value, it may suddenly change by an external I / O operation, interrupt or something"

They serve different purposes. const is more of a "wrong code rule" but a volatile "cache optimization, reordering and compilation rule"

+9


source


A possible scenario is that you have a main thread that READs statistics and an additional thread that updates statistics. Thus, the main thread would like to "get" the statistics so that they know where they are stored. This would be const

because we don't want the main thread to change the statistics, and also volatile

because the statistics are updated regularly by the secondary thread [where of course the value is not const].

const

after the function just means that it this

is a pointer const

in the function (in other words, we will not change the contents of the object in this particular function call).



Of course, the same scenario applies if stats_t

it is actually a pointer to some interesting registers in a piece of hardware that is being updated by the hardware. The compiler cannot know when / how they are updated, so one should not "assume that it never changes unless a function is called".

Edit: Please note what volatile

makes NO WAY guarantee of threads and correct operations in a multi-threaded environment. It ONLY means that the compiler will not optimize access to the variable since it has already read the value at some earlier point. To guarantee threading behavior, you really need atomic operations or locks [this is a fairly complex topic and I could probably write a few pages on this topic, and an expert could write a whole book]

+2


source







All Articles