Edit: This question dates from before C++17. These days std::launder or equivalent should be added to the line noise. I don\'t have time to update the code to match right no
Yes, this is perfectly safe and portable code.
However, there is no need to use placement new and explicit destruction in your assignment operators. Aside from it being exception safe and more efficient, I'd argue it's also much cleaner to just use the assignment operator of example_impl
:
//wrapping the casts
const example_impl& castToImpl(const unsigned char* mem) { return *reinterpret_cast(mem); }
example_impl& castToImpl( unsigned char* mem) { return *reinterpret_cast< example_impl*>(mem); }
example& example::operator=(const example& other)
{
castToImpl(this->state) = castToImpl(other.state);
return *this;
}
example& example::operator=(example&& other)
{
castToImpl(this->state) = std::move(castToImpl(other.state));
return *this;
}
Personally, I also would use std::aligned_storage instead of an manually aligned char array, but I guess thats a matter of taste.