2

Does ISO C++ (11) permit a private non-static class member variable to be optimised away? This could be detected:

class X { int x; };
assert (sizeof(X) >= sizeof(int));

but I am not aware of a clause that demands the assertion above.

To clarify: (a) Is there a clause in the C++ Standard that ensure the assertion above.

(b) Can anyone think of any other way to detect the elision of x? [offsetof?]

(c) Is the optimisation permitted anyhow, despite (a) and (b)?

I have a feeling the optimisation could be possible if the class is local to a function but not otherwise (but I'd like to have a definitive citation).

4

1 回答 1

1

我不认为这是禁止的,但我认为这是不切实际的。

§9类[类]

7/标准布局类是这样的类:

  • 没有非标准布局类(或此类类型的数组)或引用类型的非静态数据成员,
  • 没有虚函数 (10.3) 和虚基类 (10.1),
  • 对所有非静态数据成员具有相同的访问控制(第 11 条),
  • 没有非标准布局的基类,
  • 要么在派生最多的类中没有非静态数据成员,并且最多有一个具有非静态数据成员的基类,要么没有具有非静态数据成员的基类,并且
  • 没有与第一个非静态数据成员相同类型的基类。 107

8/标准布局结构是使用 class-keystruct或 class-key定义的标准布局类class

...因此class X { int x; };是标准布局结构。

§9.2 类成员 [class.mem]

16/如果两个标准布局结构(第 9 条)类型具有相同数量的非静态数据成员并且相应的非静态数据成员(按声明顺序)具有布局兼容类型(3.9),则它们是布局兼容的。

...因此class X { int x; };与布局兼容struct Y { int y; };

不幸的是,标准中没有正式定义布局兼容。然而,考虑到布局一词的使用,其意图似乎是声明两个布局兼容的类型应该具有相同的底层表示。

因此,要能够删除xin Xone 必须证明所有与布局兼容的结构(例如Y)都可以进行相同的优化(以保持布局兼容性)。在任何非平凡的程序中,这似乎都......不太可能......

于 2012-11-24T16:44:32.257 回答