简体   繁体   中英

What is volatile copy constructor for?

Could you give a trivial or real-world example to demonstrate the usage of volatile copy constructor?

I just could not come up with one.

as @Nawaz already pointed out:

When you have volatile objects, you need volatile copy-ctor. So the question boils down to this: when do you need volatile objects?

Main reason to use volatile keyword is usually to disable optimization. That is if you have something like this:

bool flag = false;
if(!flag) {}

Compiler will see that flag can't be changed so there's no need to check flag every time - so it won't. But if you make flag variable volatile - it will.

Here is an opinion of volatile keyword original use: link

In short, it was originally used to access hardware via MMIO, which may be somewhat unusual:

unsigned char* pControl = 0xff24 ;
*pControl = 0 ;
*pControl = 0 ;
*pControl = 0 ;

And you don't want those 3 assignments to become one due to optimization.

And here's a paper by Andrei Alexandrescu on volatile in multithreaded software: link

There were some papers criticizing Alexandrescu's paper, but I couldn't find it. The point there was that he was casting away volatile property and so on.

Be aware of very important thing on multithreading, pointed out by @JanHudec:

volatile is totally useless for multi-threaded context, because while it prevents optimization, it does not generate explicit barriers. And without those write done on one CPU may not become visible to another CPU (architecture dependent; x86 has coherent caches, so writes are always visible there).

Also volatile does not force the operation to be atomic. On x86 assignment is always atomic, but it's not the case with all CPU architectures. And more complex operations like increment can only be made atomic using std::atomic .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM