c++ - 为什么这个结构需要一个大小值?

标签 c++ struct sizeof

我在阅读“Beginning OpenGL Game Programming Second Edition”时遇到了这个结构定义:

typedef struct tagPIXELFORMATDESCRIPTOR 
{
    WORD  nSize;    // size of the structure
    WORD  nVersion; // always set to 1
    DWORD dwFlags;  // flags for pixel buffer properties
    ...
}

"The first of the more important fields in the structure is nSize. This field should always be set equal to the size of the structure, like this: pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); This is straightforward and is a common requirement for data structures that are passed as pointers. Often, a structure needs to know its size and how much memory has been allocated for it when performing various operations. A size field allows easy and accurate access to this information." (pg. 24)

为什么结构需要用户将大小传递给它?使用此结构的代码能否在需要时不只使用 sizeof()?

最佳答案

至少有两个可能的原因

  1. 随着使用它的库 API 的发展,结构的确切定义会随着时间而改变。新字段将添加到最后,更改结构的定义并更改其 sizeof。然而,遗留代码仍将为相同的 API 函数提供“较旧”的较小结构。为确保新旧代码都能正常工作,运行时 大小信息是必需的。从形式上讲,这就是 nVersion 字段的用途。该字段本身应该足以告诉 API 调用代码期望使用的 API 版本以及它在结构中分配了多少字段。但只是为了额外的安全性,可以通过独立的 nSize 字段提供大小信息,这不是一个坏主意。

  2. 该结构包含可选或灵活的信息(无论 API 版本如何)。填充代码将根据该大小决定您需要或不需要哪些信息,或者根据您请求的大小截断灵活大小的信息。如果结构在末尾有一个灵活的数组成员(类似于“struck hack”等),这可能特别合适。

在这种特定情况下(来自 Windows API 的 PIXELFORMATDESCRIPTOR 结构)它是适用的第一个原因,因为该结构和相关 API 没有任何灵 active 。

关于c++ - 为什么这个结构需要一个大小值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19841586/

相关文章:

C Typedef 和结构问题

c++ - 如何从文本文件中输出数据? (学生成绩单计划)

c++ - 相当于 Go 中的 sizeof(aType)

C++ 最小值和最大值

c++ - QBS为静态链接MSVC创建静态库

C++奇怪的结构和位集错误

c++ - 无论是否初始化,使用 sizeof(p[0]) 真的无害吗?

c - 指向数组的指针 - C 编程

c++ - std::advance 和 std::next 有什么区别?

c++ - 个人项目的设计建议 - "Files Renamer"?