没有定义的结构用作指针

Struct without definition used as pointer

我遇到过一些看起来像是向前声明结构的代码,但我在代码库中找不到该结构的任何定义。它似乎被使用,就像定义了结构一样。有人可以解释为什么下面的代码是有效的 c++ 吗?

框架是什么类型?尺寸是多少?我不能使用 sizeof() 因为它会抱怨它是未定义的。

我正在尝试将一段类似的代码从 2010 年转换为 Visual Studio 2015 年。reinterpret_cast 演员抱怨无法转换,因为

'reinterpret_cast': conversion from 'unsigned long' to 'Frame *' of greater size

#include <stdio.h>

struct Frame;

int main()
{
    unsigned long currentFrame = 5;
    Frame* frame = reinterpret_cast<Frame*>(currentFrame);
    printf("%p", frame);
}

GCC 4.9.2 被用来编译这个例子。

我理解错误,但不理解该结构是如何使用的。它默认为 int 吗?

程序行为是 未定义,作为从 unsigned longFrame* 的转换,其中前者设置为与指针无关的值您可以设置的值不符合 http://en.cppreference.com/w/cpp/language/reinterpret_cast.

中提到的一种可能性

printf 似乎输出指针地址这一事实是该未定义行为的表现。

Frame 不完整类型 的事实在这里无关紧要。除了 nullptr,一个超过标量地址(即单个对象或普通旧数据对象),一个超过数组末尾,将指针类型设置为内存的行为不拥有也是undefined.

由于您将 Frame 用作指针,因此编译器不需要了解有关 Frame 结构本身的任何信息。这就像使用一个不透明的指针指向某物而不关心指向的是什么。

转换失败,因为根据操作系统和数据模型(例如 LLP64 与 LP64),unsigned long 不能保证指针的大小相同。您应该考虑使用 <stdint.h> 中的 intptr_t,它保证能够存储指针的所有位,但我看不出您需要如何将文字重新解释为内存地址。