相关疑难解决方法(0)

Legit使用C/C++中的offsetof offset

有这个宏offsetof在C/C++,让您获得地址的POD结构成员的偏移.有关C FAQ的示例:

struct foo {
int a;
int b;
};

struct foo;

/* Set the b member of foo indirectly */
*(int *)((char *)foo + offsetof(b)) = 0xDEADBEEF;
Run Code Online (Sandbox Code Playgroud)

现在这对我来说似乎是邪恶的,我看不出这个宏的许多合法用途.

我看到的一个合法的例子是它在Linux内核中的container_of宏中用于获取嵌入式结构父对象的地址:

/* get the address of the cmos device struct in which the cdev
   structure which inode points to is embedded */
struct cmos_dev *cmos_devp = 
     container_of(inode->i_cdev, struct cmos_dev, cdev);
Run Code Online (Sandbox Code Playgroud)

这个宏有什么其他合法用途?你什么时候应该不会使用这个宏?

编辑到目前为止,对于一个不同的SO问题的答案是迄今为止我见过的最好的答案.

c c++ macros

8
推荐指数
3
解决办法
3309
查看次数

c ++中的struct属性继承

结构的属性是否在C++中继承

例如:

struct A {
    int a;
    int b;
}__attribute__((__packed__));

struct B : A {
    list<int> l;
};
Run Code Online (Sandbox Code Playgroud)

struct B(struct A)的继承部分是否会继承packed属性?

我不能在没有得到编译器警告的情况下向struct B 添加一个属性((packed)):

ignoring packed attribute because of unpacked non-POD field
Run Code Online (Sandbox Code Playgroud)

所以我知道整个结构B不会打包,这在我的用例中很好,但我要求struct A的字段打包在struct B中.

c++

5
推荐指数
2
解决办法
2816
查看次数

标签 统计

c++ ×2

c ×1

macros ×1