[atomic] can it bechecked that boost::atomic<T> *v = reinterpret_cast<boost::atomic<T>*>(var); is safe?
Dear experts, essentially, I use this type of reinterpret_cast for doubles, and it __seems__ to work fine. I compile-time check that the sizeof(boost::atomic<T>) == sizeof( T ), but is that enough to ensure that this will always work? Should/could I check alignment issues as well? Even if the "atomic_cast" function has a (small) run-time overhead, it would be very much worth it in my setting, where I actually want to safely add to a double at some location in memory. Obviously, I want to use boost::atomic to be system/compiler agnostic, since it's supposed to eventually run with clang, gcc, (linux, OS X) as well as MS compilers, and so far we didn't see the need to move to C++11... Thanks for any advice in advance Tim
On Monday, September 15, 2014 07:31 PM, Tim Odenthal wrote:
Dear experts,
essentially, I use this type of reinterpret_cast for doubles, and it __seems__ to work fine. I compile-time check that the sizeof(boost::atomic<T>) == sizeof( T ), but is that enough to ensure that this will always work? Should/could I check alignment issues as well? Even if the "atomic_cast" function has a (small) run-time overhead, it would be very much worth it in my setting, where I actually want to safely add to a double at some location in memory. Obviously, I want to use boost::atomic to be system/compiler agnostic, since it's supposed to eventually run with clang, gcc, (linux, OS X) as well as MS compilers, and so far we didn't see the need to move to C++11...
I'm not sure I can figure out what problem you're trying to solve. I think the cast is probably "safe", but far less can be said of it when it's dereferenced. That would depend entirely on the type of var. Is *var actually a boost::atomic<T> in the first place? If it is, why are you erasing its type? How can you be sure there is nobody else aliasing var or *var and then reading or writing it? If *var is not a boost::atomic<T>, reinterpret_cast isn't going to magically convert it, you have undefined behaviour. Of course, one effect of UB is that it __seems__ to work, until, presumably, it doesn't. Ben
participants (2)
-
Ben Pope
-
Tim Odenthal