cplusplus.co.il

Mutable and volatile

Posted on: 16/09/2009

I am a little busy nowadays, so excuse me for posting yet another somehow basic article. However, I still retain the hope that some of you are not familiar enough with at least one of these two keywords in C++.

 

Mutable

The mutable keyword can be used on a class member to allow its modification even if the object itself is constant.

Such construct should not be used lightly! Defining members as mutable breaks the whole constness idea and makes your code harder to understand and maintain. I strongly suggest using it only where (and when) it makes perfect sense.

For example, a good use for this construct is when you have some internal caching of computations. In this case, the cached data can be set mutable so that computations made through a constant object could be cached as well:

class Functor {
    public:
        uint64_t operator (uint64_t param) const {
            // some heavy calcs that read and update cache
        }
    private:
        mutable Cache m_cache;
};

 

Volatile

The volatile keyword is a type qualifier that is used to indicate that a certian object can be changed by some other mechanism but the executed program itself; Be it by the underlying operating system, hardware, or just another thread. This keeps the compiler from making any optimizations on the object that rely on inspecting your code, since your code is not the only thing that can affect it.

The following example will take a lot less time to execute if the volatile keyword is removed:

int main () {
    volatile unsigned res = 0;
    for (unsigned i=0;i<50000;++i)
        for (unsigned j=50000;j>0;--j)
            res = i >> j;
    return 0;
}

 

Reference: volatile and mutable.

Advertisements

2 Responses to "Mutable and volatile"

A question, if I may..
Why will the code run faster when not using volatile?

The compiler will see that this function return 0, and that the loop doesn’t chenges any global variable, or something like that, then it will optimize it out…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: