像在数组

时间:2016-01-20 21:58:50

标签: c++ arrays performance gcc struct

出于性能考虑,我想访问现有c ++结构的一些属性,如数组。这是我的结构类型:

struct MyStruct {
  Class1 c1;
  Class2 c2;
  MyClass myFirstAttribute, mySecondAttribute, /* ... */, myLastAttribute;
  Class3 c3;
  Class4 c4;
};

我的目标是访问MyClass类型的属性,就好像它们是一样 数组如:

struct MyStruct {
  Class1 c1;
  Class2 c2;
  MyClass myArray[20];
  Class3 c3;
  Class4 c4;
};

MyClass类只包含1个成员(double)。到目前为止,我 写了下面的函数,它似乎工作,但我想知道我是不是幸运的是属性按预期对齐:

MyClass& accessElement(struct MyStruct &s, int index)
{
  MyClass *myArray = &s.myFirstAttribute;
  return myArray[index];
}

的原因

请注意,这只是暂时的,我知道最好直接使用 一个数组,但它需要相当多的更改,但我需要进行更改 透明,因为我没有使用这个结构管理所有代码。而且, 改变背后的原因是因为以前的功能 使用switch语句实现,并编译为if - then - else 声明。我正在使用gcc 4.3编译-std = c ++ 98和-O2选项。

加成

我还尝试了其他一些技巧,但它没有奏效,因为我正在玩一个 非常大而复杂的代码,例如:

  • 将数组添加为属性,并将属性更改为引用 指向数组的相应索引。这不起作用 它需要代码中某处的复制构造函数,我需要 实现它,这是非常挑剔的(结构更多 复杂)。
  • 使用define宏自动替换名称为的所有字符串 我希望用索引替换相应的数组(参见 下面)。这不能作为代码的另一部分中的一些变量 与属性具有相同的名称。

使用define:

#define myFirstAttribute myArray[0]
#define mySecondAttribute myArray[1]
#define myLastAttribute myArray[20]

Qestions

还有其他想法吗?或者,有什么方法可以让我的黑客更安全,以确保它按预期编译?

修改

正如所建议的那样in this post(感谢@Thomas Matthews的链接),查找表会更好,但是你支付间接费用(我认为与虚函数相同)。我想知道这样的事情是否合法:

struct MyStruct {
  Class1 c1;
  Class2 c2;

  union {
    struct {
      MyClass myFirstAttribute, mySecondAttribute, /* ... */, myLastAttribute;
    };
    MyClass myArray[];
  };
  Class3 c3;
  Class4 c4;
};

这似乎有效,并且在其他帖子中没有提示。我需要打包匿名结构吗?有什么建议吗?

0 个答案:

没有答案