简体   繁体   English

强制对sizeof运算符进行编译时错误

[英]Force compile time error on sizeof operator

Sometimes we have a POD struct whose sizeof has a meaning for serialization purposes. 有时我们有一个POD结构,其sizeof具有序列化含义。 From my PE parser, from example: 从我的PE解析器中,例如:

struct dos_header {
    unsigned short magic;
    unsigned short cblp;
    ...
    };

This structure is meant to be serialized from/to the PE image, so sizeof on it has a meaning on, say, ifstream::read . 该结构是要从PE映像/到PE映像进行序列化的,因此它的sizeofifstream::read上具有含义。

This is invalid of course for non POD. 对于非POD,这当然是无效的。 The nt_header for example: nt_header例如:

struct nt_header 
{
    std::uint32_t Signature;
    file_header FileHeader;
    std::variant<optional_header_32, optional_header_64> OptionalHeader;
}

Serializing with sizeof would be valid technically, but nonsense at runtime because the size of the structure is run-time dependent. 从技术上讲,使用sizeof进行序列化是有效的,但是在运行时却毫无意义,因为结构的大小取决于运行时。

Is there a way to force the compiler to generate a compile time error when sizeof is used in such a class? 当在此类中使用sizeof时,是否有一种方法可以强制编译器生成编译时错误?

So, if I accidentally use sizeof(nt_header) somewhere, the compiler warns me. 因此,如果我不小心在某处使用sizeof(nt_header) ,则编译器会警告我。

There's no getting around the fact that using even nt_header for memcpy is fine so long as the alternatives are trivially copyable. 有回避的事实,即使使用没有得到nt_headermemcpy是罚款,只要替代品平凡可复制。 If that's not the serialization mechanism you want to use for such objects… don't? 如果那不是您要用于此类对象的序列化机制,是吗? It's easy to provide a template that handles all your (de)serialization and is specialized to sometimes read less data (and, here, to compute the variant 's index from some other contextual information). 提供一个处理所有(反)序列化的模板很容易,并且专门用于有时读取较少的数据(并在此处根据一些其他上下文信息来计算variant的索引)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM