gpt4 book ai didi

c++ - 标准布局类型和 reinterpret_cast

转载 作者:行者123 更新时间:2023-11-30 02:07:46 24 4
gpt4 key购买 nike

如果我已将结构的成员复制到我的类中,我是否可以从我的类转换为结构?

#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);
}
}

最佳答案

首先,你不能抛弃常量:

§5.2.10p2. The reinterpret_cast operator shall not cast away constness (§5.2.11). (...)

所以你至少需要这样写

operator iovec const*() const
{
return reinterpret_cast<iovec const*>(this);
}

operator iovec *()
{
return reinterpret_cast<iovec *>(this);
}

最重要的是,您需要同时拥有 Bufferiovec是标准布局类型,iovec不能有比 Buffer 更严格(即更大)的对齐方式.

§5.2.10p7. An object pointer can be explicitly converted to an object pointer of a different type. When a prvalue v of type “pointer to T1” is converted to the type “pointer to cv T2”, the result is static_cast<cv T2*>(static_cast<cv void*>(v)) if both T1 and T2 are standard-layout types (§3.9) and the alignment requirements of T2 are no stricter than those of T1, or if either type is void. (...)

您还需要注意不要破坏 strict aliasing rules : 通常,您不能使用指向同一内存位置的不同类型的两个指针或引用。

关于c++ - 标准布局类型和 reinterpret_cast,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7507818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com