为什么我不能返回对压缩字段的引用? [英] Why can't I return a reference to a packed field?

查看:172
本文介绍了为什么我不能返回对压缩字段的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用g ++编译带有压缩字段的代码。但是,尝试返回对打包字段的引用时收到错误消息。

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

示例:

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

收益率错误:

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?

推荐答案

有gcc错误报告无法绑定包含此内容的压缩字段,并说:

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


C ++规范(C ++ 03,第3.9节) ,3.9.1、3.9.2)非常清楚,T和 T的指针有特定于实现的对齐要求。如果您有 T的指针,那么您可以假定它满足对齐要求。我确定C规范具有类似的语言。

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.

在OP的情况下,以下代码可能违反对齐要求

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

他们建议使用 alignment 属性定义您自己的对齐类型的解决方法,但是它看起来并不可行。

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

这篇关于为什么我不能返回对压缩字段的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆