Am I allowed to cast from my class to a structure if i have copied the members of the structure to my class?
#include <stdint.h>
#include <sys/uio.h>
class Buffer
{
public:
void * address;
size_t size;
Buffer(void * address = nullptr, size_t size = 0)
: address(address), size(size)
{
}
operator iovec *() const
{
// Cast this to iovec. Should work because of standard layout?
return reinterpret_cast<iovec *>(this);
}
}
First off, you cannot cast away constness:
So you need at least to write that as
or
On top of that, you need to have both
Bufferandiovecbe standard-layout types, andioveccannot have an alignment stricter (i.e. larger) thanBuffer.You also need to be careful not to break the strict aliasing rules: in general, you cannot use two pointers or references to different types that refer to the same memory location.