我正在研究如何在C++中将成员的内存偏移量转换为类,并在维基百科上看到了这一点:
在C++代码中,您不能使用offsetof来访问非Plain Data Data Structures的结构或类的成员.
我尝试了它似乎工作正常.
class Foo
{
private:
int z;
int func() {cout << "this is just filler" << endl; return 0;}
public:
int x;
int y;
Foo* f;
bool returnTrue() { return false; }
};
int main()
{
cout << offsetof(Foo, x) << " " << offsetof(Foo, y) << " " << offsetof(Foo, f);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到了一些警告,但它已经编译,运行时它给出了合理的输出:
Laptop:test alex$ ./test
4 8 12
Run Code Online (Sandbox Code Playgroud)
我想我要么误解POD数据结构是什么,要么我错过了其他一些难题.我不知道问题是什么.
从下面的代码sizeof(Base) == 24和sizeof(Derived) == 24.
为什么他们的尺寸相同?
在Base课堂上我们有3名成员,在Derived课堂上我们有另一名成员.
class Base
{
private:
double d;
protected:
long l;
public:
int i;
};
class Derived : public Base
{
private:
float f;
};
Run Code Online (Sandbox Code Playgroud) 在为32位x86 linux运行以下代码时,我得到了意想不到的结果(编译器标志:g ++ -std = c ++ 14 -m32).我试过gcc和clang.
#include <iostream>
using namespace std;
struct S1
{
uint64_t a;
uint32_t b;
};
struct S2
{
alignas(uint64_t) char a[8];
uint32_t b;
};
int main()
{
cout << "sizeof(S1)=" << sizeof(S1) << endl;
cout << "sizeof(S2)=" << sizeof(S2) << endl;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
sizeof(S1)=12
sizeof(S2)=16
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?为什么S1和S2的尺寸不同?据我了解,64位整数值在32位x86机器上与32位对齐.这解释了为什么S1的大小是12个字节.但为什么这不适用于S2呢?