gpt4 book ai didi

c++ - 使用 offsetof 有什么问题?

转载 作者:IT老高 更新时间:2023-10-28 21:50:48 26 4
gpt4 key购买 nike

我正在 MinGW GCC 4.4.0 中编译一些 c++ 代码,并收到以下形式的警告...

warning: invalid access to non-static data member '<membername>'  of NULL object
warning: (perhaps the 'offsetof' macro was used incorrectly)

这个问题似乎很熟悉——我之前尝试过解决但失败了,我想,但不久前。该代码在 Visual C++ 中构建良好,但我最近没有在任何其他编译器中构建此特定代码。

问题代码如下模板...

template<typename T>
class c_Align_Of
{
private:
struct c_Test
{
char m_Char;
T m_Test;
};
public:
enum { e_Align = offsetof (c_Test, m_Test) };
};

显然我可以使用一些条件编译来为此使用编译器特定的函数,并且我相信 C++0x 将(最终)使其变得多余。但无论如何,我看不出这种使用 offsetof 有什么问题。

非常迂腐,有可能因为 T 参数类型有时是非 POD,所以 GCC 将 c_Test 归类为非 POD 和提示(并且提示和提示 - 我收到了近 800 行这些警告)。

这对于标准的严格措辞来说是很顽皮的,因为非 POD 类型可能会破坏 offsetof。但是,这种非 POD 在实践中应该不是问题 - c_Test 不会有虚拟表,并且不需要运行时技巧来找到 m_Test< 的偏移量

此外,即使 c_Test 有一个虚拟表,GCC 也使用一个内在函数来实现 offsetof 宏,该内在函数总是在编译时根据该特定类型的静态布局进行评估。提供一个工具,然后每次使用它时都会提示(抱歉,警告)看起来很愚蠢。

而且,我不是这里唯一一个做这种事情的人......

Answer to legit-uses-of-offsetof question

确实记得由于这种原因,offsetof 有问题,但我不认为问题出在这个模板上。

有什么想法吗?

最佳答案

哎呀...

问题 ,由于 T 类型是非 POD,因此 c_Test 结构是非 POD。这是来自 GCC 手册的引述...

-Wno-invalid-offsetof (C++ and Objective-C++ only)

Suppress warnings from applying the ‘offsetof’ macro to a non-POD type.

According to the 1998 ISO C++ standard, applying ‘offsetof’ to a non-POD type is undefined. In existing C++ implementations, however, ‘offsetof’ typically gives meaningful results even when applied to certain kinds of non-POD types. (Such as a simple ‘struct’ that fails to be a POD type only by virtue of having a constructor.) This flag is for users who are aware that they are writing nonportable code and who have deliberately chosen to ignore the warning about it.

The restrictions on ‘offsetof’ may be relaxed in a future version of the C++ standard.

我的问题是我几乎所有的 T 类型都有构造函数,因此被归类为非 POD。我之前忽略了这一点,因为它无关紧要——当然,原则上它应该与 offsetof 无关。问题是 C++ 标准使用一种 POD 与非 POD 分类,即使有许多不同的方式可以成为非 POD,并且编译器在默认情况下警告不符合标准的使用是正确的。

我目前的解决方案是上面的选项来抑制警告 - 现在我只需要弄清楚如何告诉 cmake 使用它。

关于c++ - 使用 offsetof 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3129916/

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