指向 POD 结构的 C/C++ 指针也指向第一个结构成员 [英] C/C++ Pointer to a POD struct also points to the 1st struct member

查看:22
本文介绍了指向 POD 结构的 C/C++ 指针也指向第一个结构成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以假设 C/C++ 结构指针将始终指向第一个成员吗?
示例 1:

Can I assume that a C/C++ struct pointer will always point to the first member?
Example 1:

typedef struct {
 unsigned char  array_a[2];
 unsigned char  array_b[5];
}test;
//..
test var;
//..

在上面的例子中 &var 总是指向 array_a 吗?同样在上面的例子中,可以将指针转换为到无符号字符指针并分别访问每个字节?
示例 2:

In the above example will &var always point to array_a? Also in the above example is it possible to cast the pointer to an unsigned char pointer and access each byte separately?
Example 2:

function((unsigned char *)&var,sizeof(test));
//...
//...
void function(unsigned char *array, int len){
 int i;
 for( i=0; i<len; i++){
    array[i]++;
 }
}

这能正常工作吗?

注意:我知道字符在结构中是字节对齐的,因此我假设上述结构的大小为 7 个字节.

Note: I know that chars are byte aligned in a struct therefore I assume the size of the above struct is 7 bytes.

推荐答案

对于 C 结构,是的,您可以依赖它.这就是几乎所有面向对象"风格的 API 在 C 中的工作方式(例如 GObject 和 GTK).

For C structs, yes, you can rely on it. This is how almost all "object orientated"-style APIs work in C (such as GObject and GTK).

对于 C++,您只能将它用于普通旧数据"(POD) 类型,这些类型保证在内存中的布局方式与 C 结构相同.POD 类型的确切构成有点复杂,并且在 C++03 和 C++11 之间发生了变化,但关键是如果您的类型有任何虚函数,那么它就不是 POD.

For C++, you can rely on it only for "plain old data" (POD) types, which are guaranteed to be laid out in memory the same way as C structs. Exactly what constitutes a POD type is a little complicated and has changed between C++03 and C++11, but the crux of it is that if your type has any virtual functions then it's not a POD.

(在 C++11 中,您可以使用 std::is_pod 在编译时测试结构是否为 POD 类型.)

(In C++11 you can use std::is_pod to test at compile-time whether a struct is a POD type.)

这告诉你什么构成了 C++ 中的 POD 类型:http://en.cppreference.com/w/cpp/concept/PODType

This tells you what constitutes a POD type in C++: http://en.cppreference.com/w/cpp/concept/PODType

实际上,在 C++11 中,它不需要是 POD,只是标准布局",这是一个稍微弱一些的条件.引用标准第9.2节[class.mem]第20段:

Actually, in C++11, it doesn't need to be a POD, just "standard layout", which is a lightly weaker condition. Quoth section 9.2 [class.mem] paragraph 20 of the standard:

一个指向标准布局结构对象的指针,使用 reinterpret_cast 适当转换,指向它的初始成员(或者如果该成员是位字段,则为它所在的单元),反之亦然.[ 笔记:因此,标准布局结构对象中可能存在未命名的填充,但不是在其开头,必要时实现适当的对齐.— 尾注 ]

A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. — end note ]

这篇关于指向 POD 结构的 C/C++ 指针也指向第一个结构成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆