How does one do a placement new operation on a volatile pointer.
For example, I want to do something like this:
volatile SomeStruct Object;
volatile SomeStruct* thing = &Object;
new (thing) SomeStruct(/*arguments to SomeStruct's constructor*/);
I know this would work if there was no volatile keyword......but how can I do this with a volatile variable?
Note:
Placement new is defined like this:
void* operator new(size_t memoryRequested, void* pointer)
{
return pointer;
}
(By the way here is how GCC implements it):
// Default placement versions of operator new.
inline void* operator new(std::size_t, void* __p) _GLIBCXX_USE_NOEXCEPT
{ return __p; }
The problem is that I am trying to convert thing
of type volatile SomeStruct*
to void*
, which is not allowed.
For example if I change the new operator to this:
void* operator new(size_t memoryRequested, volatile void* pointer)
{
return (void*)pointer;
}
It would compile, but would invoke undefined behavior.
I want to say you can do it like this:
new (const_cast<SomeStruct*>(thing)) volatile SomeStruct(...);
But I'm not actually sure whether this is valid or not. The problem is that since the allocation function returns a void*
into which to construct the volatile SomeStruct
object, accesses to the memory may not have volatile semantics, leading to undefined behavior.
So I'm not sure whether it's legal to use placement new to construct an object into a volatile-qualified block of memory. However, assuming the memory was originally, say, a non-volatile array of char
, this seems like the correct solution.