Most of the time, I am doing this way.
class a {
public:
~ a() {
i = 100; // OK
delete (int *)j; // Compiler happy. But, is it safe?
// The following code will lead compilation error : delete j;
}
private:
volatile int i;
volatile int *j;
};
int main() {
a aa;
}
However, I saw an article here:
https://www.securecoding.cert.org/confluence/display/seccode/EXP32-C.+Do+not+access+a+volatile+object+through+a+non-volatile+reference
Casting away volatile allows access to an object through a non-volatile reference. This can result in undefined and perhaps unintended program behavior.
So, what will be the workaround for my above code example?
Here is the error message I get if I use
delete j
Note that, this is output from VC6 (Don't ask why I am using VC6!)
c:\projects\a\a.cpp(5) : error C2664: 'delete' : cannot convert parameter 1 from 'volatile int *' to 'void *' Conversion loses qualifiers
Nothing. If you don't access the volatile memory, the semantics of volatile are unaffected. If you accessed volatile memory through a casted non-volatile pointer, the compiler might optimize the reference away. If the value had changed, you'd have the wrong value. For some value of wrong. ;-)
The delete doesn't access the volatile memory, it just frees it. Sort of an uncommon thing to do with volatile memory.
delete
ing a volatile
would imply that you've serialized access to it so it is not, in fact, volatile
any more. The proper way to remove the volatile (once you know it's safe) is with const_cast<int*>
.
If the pointer, and not the int
, is volatile, then you really meant int *volatile j
. Moreover, if all the members of a class are volatile, you probably want to qualify the entire object at once, a volatile aa;
.
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