Use of Union with reference

前端 未结 2 1648
野趣味
野趣味 2021-01-05 04:12

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: (Sim

相关标签:
2条回答
  • 2021-01-05 04:56

    It is illegal for a union to contain a reference member. This is presumably because references are not objects and it's unspecified whether or not they occupy storage---so it makes little sense for a reference to share its storage with other variables.

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

    ([class.union]/2)

    0 讨论(0)
  • 2021-01-05 05:11

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

    live example

    0 讨论(0)
提交回复
热议问题