Is the definition of “volatile” this volatile, or is GCC having some standard compliancy problems?

前端 未结 4 1515
醉酒成梦
醉酒成梦 2020-12-13 01:32

I need a function that (like SecureZeroMemory from the WinAPI) always zeros memory and doesn\'t get optimized away, even if the compiler thinks the memory is never going to

4条回答
  •  情深已故
    2020-12-13 02:04

    I offer this version as portable C++ (although the semantics are subtly different):

    void volatileZeroMemory(volatile void* const ptr, unsigned long long size)
    {
        volatile unsigned char* bytePtr = new (ptr) volatile unsigned char[size];
    
        while (size--)
        {
            *bytePtr++ = 0;
        }
    }
    

    Now you have write accesses to a volatile object, not merely accesses to a non-volatile object made through a volatile view of the object.

    The semantic difference is that it now formally ends the lifetime of whatever object(s) occupied the memory region, because the memory has been reused. So access to the object after zeroing its contents is now surely undefined behavior (formerly it would have been undefined behavior in most cases, but some exceptions surely existed).

    To use this zeroing during an object's lifetime instead of at the end, the caller should use placement new to put a new instance of the original type back again.

    The code can be made shorter (albeit less clear) by using value initialization:

    void volatileZeroMemory(volatile void* const ptr, unsigned long long size)
    {
        new (ptr) volatile unsigned char[size] ();
    }
    

    and at this point it is a one-liner and barely warrants a helper function at all.

提交回复
热议问题