Why can't I return a reference to a packed field?

有些话、适合烂在心里 提交于 2019-12-06 19:33:15

问题


I use g++ to compile code with packed fields. However, I receive an error when trying to return a reference to a packed field.

Example:

struct __attribute__((packed)) Foo {
   int* ptr;
   uint16_t foo;
   int*& getPtr(){
      return ptr;
   }
};

yields error:

test.cpp:22:14: error: cannot bind packed field ‘((Foo*)this)->Foo::ptr’ to ‘int*&’
   return ptr;

Why can't I return a reference to a packed field?


回答1:


There is a gcc bug report Cannot bind packed field that covers this and it says:

The C++ spec (C++03, Sects. 3.9, 3.9.1, 3.9.2) are very clear that T and "pointer to T" have implementation-specific alignment requirements. If you have a "pointer to T" then you may assume that it meets the alignment requirements. I'm sure the C spec has similar language.

In the OP's case, the following code could violate the alignment requirements

They suggest a workaround using alignment attribute to define your own aligned type but it does not look like it works.



来源:https://stackoverflow.com/questions/27491432/why-cant-i-return-a-reference-to-a-packed-field

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