Do data members form a range?

僤鯓⒐⒋嵵緔 提交于 2019-12-23 06:53:58

问题


Can I treat consecutive data members of the same type as a range? For example:

struct X
{
    int a, b, c, d, e;
};

X x = {42, 13, 97, 11, 31};

std::sort(&x.a, &x.a + 5);   // kosher?

回答1:


No, this is undefined behaviour. You are treating x.a like the first element of an array, which it isn't. May work on some implementations, may raid your fridge too ;)




回答2:


Don't do that. Compiler is free to add paddings between structure members(and at the end).




回答3:


If this is really something you want to do, make it an array, vector or similar.

As others have said, the standard makes no guarantees about the members being stored without gaps or otherwise things that cause problems. (And to make matters worse, it will appear to work, until you compile it with a different (version of) compiler, or for another architecture some months or years later, and of course, it won't be easy to figure out what went wrong).




回答4:


No, this is not possible in C++. It would be rather difficult to standarize; in this case the semantic is simple enough, but what if the struct was heterogenous?




回答5:


Generally, it's a bad idea. If you want to treat some variables as array, you should declare them as array :)

Nevertheless you can use some compiler-specific instruction to ensure that there is no padding between elements, f.i.:

#pragma pack(push, 1)  
struct X
{
    int a, b, c, d, e;
};
#pragma pack(pop)

or

struct  __attribute__((__packed__)) X
{
    int a, b, c, d, e;
};


来源:https://stackoverflow.com/questions/18635981/do-data-members-form-a-range

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!