Is It Safe to Cast Away volatile?

c++

Solution

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.

Problem

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

Original source