使用联盟作为参考 [英] Use of Union with reference
问题描述
在工作中,我一直在使用Linux和C ++ 11和C ++ 14的GCC编译器.在工作中的某些代码中,我使用联合来存储引用和指针,如下所示:(简化为重要部分)
At work I've been using linux and the GCC compiler for C++11 and C++14. In some of the code at work, I've used a union to store both a reference and a pointer, as so: (Simplified to just the important parts)
struct MyStruct
{
//Stuff
union { double& x; double* x_ptr; };
MyStruct(double& value) : x(value) {}
//More stuff
};
我相信这段代码清晰,可读,明确,并提供了一种方便的方式来存储可以转移到其他地方的引用.它提供易于理解的语法糖,而不会提高性能,同时又提高了可读性.但是,当我尝试在Visual Studio 15中使用这样的代码时,由于"double&类型的非法联合成员",代码无法编译.
I believe this code is clear, readable, unambiguous, and provides a convenient way to store references which can be shifted to something else. It provides easily understandable syntactic sugar without costing performance while improving readability. When I attempted to use code like this in visual studio 15, however, the code failed to compile due to "an illegal union member of type double&".
- 此代码在标准下还是在Visual Studio 2015下是非法的?
- 我可以在Visual Studio 2015中对其进行编译,还是可以提交错误报告/更改请求/内容?
- 以这种方式使用工会是不好的做法吗?
注意:在我的工作中,几乎所有代码都是为Linux编写并使用GCC编译的,对于我的特定项目,可以保证C ++ 11,而GCC是唯一将要使用的编译器.
Note: At my work, pretty much all code is written for Linux and compiled with GCC, and for my specific project, C++11 is guaranteed and GCC is the only compiler that's going to be used.
编辑:请不要告诉我,将引用放在联合体内没有任何意义".当引用存储在结构内部时,它占用的空间与指针相同.此外,以下使用clang进行编译:
Please don't tell me that putting a reference inside a union "has no meaning". When a reference is stored inside a struct, it takes up the same amount of space as a pointer. In addition, the following compiles with clang:
struct MyStruct
{
//This will compile
union
{
struct { double& x; };
double* x_ptr;
};
//This won't compile; WHY?
/*union
{
double& x;
double* x_ptr;
};*/
MyStruct(double& val) : x(val){}
void Repoint(double& new_value)
{
x_ptr = &new_value;
}
};
为什么将引用包装在匿名结构中而不是仅在联合中时编译?
Why does it compile when the reference is wrapped in an anonymous struct, but not when it's just in the union?
推荐答案
除了@Brian:您可以使用例如 std :: reference_wrapper
而不是简单的引用:
In addition to @Brian:
You can make it compile by using e.g. std::reference_wrapper
instead of a plain reference:
#include <functional>
struct MyStruct
{
//Stuff
union { std::reference_wrapper<double> x; double* x_ptr; };
MyStruct(double& value) : x(value) {}
//More stuff
};
int main()
{
double value = 123;
MyStruct myStruct(value);
}
这篇关于使用联盟作为参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!