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.
A copy constructor in a Java class is a constructor that creates an object using another object of the same Java class. That's helpful when we want to copy a complex object that has several fields, or when we want to make a deep copy of an existing object.
Advantages of Copy ConstructorIf a field declared as final, the copy constructor can change it. There is no need for typecasting. Its use is easier if an object has several fields. Addition of field to the class is easy because of it.
You cannot declare a constructor as virtual or static , nor can you declare a constructor as const , volatile , or const volatile . You do not specify a return type for a constructor.
When to delete copy constructor and assignment operator? Copy constructor (and assignment) should be defined when ever the implicitly generated one violates any class invariant. It should be defined as deleted when it cannot be written in a way that wouldn't have undesirable or surprising behaviour.
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 usingstd::atomic
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With