Using Union with reference

At work, I used linux and the GCC compiler for C ++ 11 and C ++ 14. In some of the code at work, I used a union to store both the link and the pointer, like so: (Simplified only for important parts)

struct MyStruct { //Stuff union { double& x; double* x_ptr; }; MyStruct(double& value) : x(value) {} //More stuff }; 

I believe this code is clear, readable, unambiguous, and provides a convenient way to store links that can be carried over to something else. It provides easy-to-understand syntactic sugar without cost-effectiveness while improving readability. However, when I tried to use such code in visual studio 15, the code could not be compiled due to the "illegal member of the double & union type".

  • Is this code illegal by standard or only under Visual Studio 2015?
  • Can I compile it in Visual Studio 2015 or send an error report / change request / something?
  • Is using the union in this way a bad practice?

Note. In my work, almost all the code is written for Linux and compiled with GCC, and for my specific project, C ++ 11 is guaranteed, and GCC is the only compiler to be used.

Edit: Please do not tell me that setting the link inside the union "makes no sense." When a link is stored inside a structure, it takes up as much space as the pointer. In addition, the following compilation 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 is it compiled when the link is authenticated in an anonymous structure, but not when it is only in union?

living example

+6
source share
2 answers

In addition to @Brian: You can compile it using, for example, std::reference_wrapper instead of a simple link:

 #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); } 

living example

+9
source

The union is prohibited from containing a reference element. This is apparently because the links are not objects, and they are not indicated whether they occupy storage or not, so it makes no sense to refer to its storage with other variables.

A union can have member functions (including constructors and destructors), but not virtual (10.3) functions. The union should not have base classes. A union should not be used as a base class. If the union contains a non-static data member of the reference type, the program is poorly formed.

([class.union] / 2)

+8
source

All Articles