标准布局类型和reinterpret_cast
如果我已将结构体的成员复制到我的类中,是否可以从我的类转换为结构体?
#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);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,你不能抛弃常量:
所以你至少需要将其写为
or
最重要的是,你需要让
Buffer
和iovec
都是标准布局类型,并且 < code>iovec 的对齐方式不能比Buffer
更严格(即更大)。您还需要小心,不要违反严格的别名规则:一般来说,您不能使用两个指向引用同一内存位置的不同类型的指针或引用。
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
Buffer
andiovec
be standard-layout types, andiovec
cannot 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.