类对象数组中的c ++内存 [英] c++ memory in array of class objects

查看:129
本文介绍了类对象数组中的c ++内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的类:

class Object {
public: 
    unsigned char data[8];
    // other variables
    // functions etc...
 };

问题是 - 对象成员是否都存储在内存中相对于对象的相同位置?所以如果我有一个数组:Object array [3],给定一个char指针
char * data_ptr = array [0] .data ,将
data_ptr +(sizeof(Object))然后总是指向array [1] .data?

The question is - are the object members all stored in the same place in memory relative to the object? So if I have an array: Object array[3], given a char pointer char* data_ptr = array[0].data, will data_ptr + (sizeof(Object)) then always point to array[1].data?

关于如何在类和结构体的数据成员之间可能有填充 - 但我不认为他们回答我的问题。)

(I've read a couple of Q/As about how there might be padding inbetween data members of classes and structs - but I don't think they answer my question.)

谢谢提前,
Ben

Thanks in advance, Ben

推荐答案

sizeof Object Object 的所有内部填充。包括在其末端的任何填充。数组不允许任何附加的填充。因此, data_ptr + sizeof Object 的地址应该为 array [1] .data

sizeof Object already includes all internal padding of the class Object. including any padding at its end. Arrays don't allow any additional padding. Therefore it is true that data_ptr + sizeof Object will have the address of array[1].data.

我不知道这是否真的被允许。也就是说,可以允许编译器 假设您从未将大于8的值(成员数组的大小 data )添加到 array [0] .data ,因此如果违反规则,它可能会应用失败的优化。也就是说,你的代码可能实际上表现出未定义的行为(这是编译器允许在这种情况下做任何事情的标准术语)。

However I'm not sure if this is actually allowed. That is, the compiler might be allowed to assume that you never add a value larger than 8 (the size of the member array data) to array[0].data, and therefore it might apply optimizations that fail if you violate the rules. That is, your code might actually exhibit undefined behavior (which is the standard term for "the compiler is allowed to do anything in this case").

因为您使用的是 char 的指针,其中有更多的允许规则(您可以使用 char * 你不能用一般类型),它可能是它实际上定义的行为。

However since you are using a pointer to char, for which there are more permissive rules (you can do many things with char* which you could not do with general types), it may be that it's actually defined behaviour anyway.

这篇关于类对象数组中的c ++内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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