如何使用 __attribute__((__packed__)) 结构的成员更正有关 g++ 引用参数的错误?
How to correct a error about g++'s reference parameter with __attribute__((__packed__)) struct's member?
在我问了一个类似的问题之后,我进一步尝试在打包结构中更简单的成员变量,我得到了同样的错误。我很困惑!
编译以下代码时:
struct TupleHeader {
int tuple_stime;
}__attribute__((__packed__));
void set_value(int& stime){
}
int main(){
TupleHeader tuple;
set_value(tuple.tuple_stime);
return 0;
}
我收到错误:
[borealis@localhost cpp-program]$ g++ attribute-1.cc
attribute-1.cc: In function `int main()':
attribute-1.cc:13: error: cannot bind packed field `tuple.TupleHeader::tuple_stime' to `int&'
将函数定义set_value(int& stime)
更改为set_value(int stime)
后,错误消失了。我想问一下除了修改set_value(int& stime)
还有其他方法吗?
据我所知,您的解决方案甚至不是有效的解决方案,因为通过应用它,您完全破坏了您的程序。
最好的办法是发送对整个TupleHeader
的引用,并在set_value
内访问.tuple_stime
......当然,在给它一个描述性名称之后。
GCC 似乎并没有抱怨#pragma pack
#pragma pack(push, 1)
struct TupleHeader {
int tuple_stime;
};
#pragma pack(pop)
另一种选择是演员表
set_value(reinterpret_cast<int&>(tuple.tuple_stime));
根据您的平台对齐要求,两者都可能是不安全的(即您可能不应该首先这样做(。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- 如何引用基类的派生类?