This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: warning: invalid offsetof from non-POD type
John Quigley <johnw at lowestplane dot org> writes:
> Here you go. Note that it is a warning, not an error.
>
> // BEGIN CODE
> #include <cstddef>
> #include <iostream>
> using namespace std;
>
> class Foo
> {
> public:
> int x;
> char fillerdata[256];
> int y;
>
> Foo()
> {
> x = 0;
> y = 0;
> }
> };
>
> int main()
> {
> int yoffset = offsetof(Foo, y); // triggers warning
> cout << "yoffset: " << yoffset << endl;
>
> Foo foo;
>
> // get a pointer to y using the computed offset
> int* yptr = (int*)(((unsigned char*)&foo) + yoffset);
> // test it by assigning value
> *yptr = 15;
> cout << "foo values: " << foo.x << ", " << foo.y << endl;
>
> return 0;
> }
> // END CODE
The C++ Standard says that offsetof is only required to work for POD
types. The warning is remembering that to you.
--
Oscar