本文介绍了命名数组元素或联合中的结构和数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下结构:

struct Vector4D
{
   union
   {
      double components[4];
      struct { double x, y, z, t; } Endpoint;
   };
};

在我看来,我在WinApi的IPAddress结构中看到了类似的内容.这个想法是让我可以同时使用索引和名称来使用数组组件,例如:

It seems to me that I have seen something similar in WinApi's IPAddress struct. The idea is to give me the possibility to use the array components both by index and by name, for example:

Vector4D v;
v.components[2] = 3.0;
ASSERT(v.Endpoint.z == 3.0) //let's ignore precision issues for now

在C ++标准中,可以保证POD结构的开头没有空"空间,也就是说,元素x恰好位于Endpoint结构的beginnig中.目前很好.但是我似乎找不到任何保证,如果有的话,在xy之间,或者在yz之间将没有空白或填充.我尚未签出不过是C99标准.

In the C++ standard there is a guarantee that there will be no "empty" space at the beginning of a POD-struct, that is, the element x will be situated right in the beginnig of the Endpoint struct. Good so far. But I don't seem to find any guarantees that there will be no empty space or padding, if you will, between x and y, or y and z, etc. I haven't checked out the C99 standard though.

问题在于,如果Endpoint结构元素之间没有空格,那么该想法将行不通.

The problem is that if there is an empty space between Endpoint struct elements, then the idea will not work.

问题:

Questions:

  1. 我是对的,实际上并不能保证它可以在C或C ++中正常工作.

  1. Am I right that there indeed is no guarantee that this will work either in C or C++.

这将在任何已知的实现上切实可行吗?换句话说,您知道在其中不起作用的任何实现吗?

Will this practically work on any known implementation? In other words, do you know of any implementation where this doesn't work?

是否有任何标准的方法(我的意思不是特定于编译器的方法)来表达相同的想法?也许C ++ 0x对齐功能可能会有所帮助?

Is there any standard(I mean not compiler-specific) way to express the same idea? Maybe the C++0x alignment features might help?

顺便说一句,这不是我在生产代码中正在做的事情,不用担心,只是好奇.预先感谢.

By the way, this isn't something I am doing in production code, don't worry, just curious. Thanks in advance.

推荐答案

  1. 取决于架构的对齐需求和编译器策略
  2. 否,但是您可以做一个对象包装器(但最终会得到.z()而不是仅.z)
  1. yes
  2. depends on the alignment needs of the architecture and the compilers strategy
  3. no, but you could make a object wrapper (but you will end up with .z() instead of just .z)

大多数编译器应支持使用杂注或属性压缩结构.例如#pragma pack.

Most compilers should support squashing a structure using a pragma or an attribute. #pragma pack for example.

这篇关于命名数组元素或联合中的结构和数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 07:21