Use of Union with reference

China☆狼群 提交于 2019-12-04 05:03:32

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

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!