可以优化C类内部参考的存储吗?

前端之家收集整理的这篇文章主要介绍了可以优化C类内部参考的存储吗?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
C语言是否允许以下​​代码打印,例如1而不是16?根据其他答案,我猜是的,但这个案例似乎没有被覆盖.
  1. #include "iostream"
  2. #include "cstdlib"
  3. using namespace std;
  4.  
  5. struct as_array {
  6. double &a,&b;
  7.  
  8. as_array(double& A,double& B)
  9. : a(A),b(B) {}
  10.  
  11. double& operator[](const int i) {
  12. switch (i) {
  13. case 0:
  14. return this->a;
  15. break;
  16. case 1:
  17. return this->b;
  18. break;
  19. default:
  20. abort();
  21. }
  22. }
  23. };
  24.  
  25. int main() {
  26. cout << sizeof(as_array) << endl;
  27. }

解决方法

标准在[dcl.ref]下说:

It is unspecified whether or not a reference requires storage

此外,由编译器决定对象的大小,因此您可以在此处获得任何非零数字.

还有as-if规则(也称为优化权限).因此,当且仅当使用引用的方式需要时,编译器才能将存储用于这些引用是合法的.

说了这么多;为了获得稳定的ABI,我仍然希望编译器为这些引用分配存储.

猜你在找的C&C++相关文章