Unions in C++11: default constructor seems to be deleted

江枫思渺然 提交于 2019-12-03 11:28:41

The cppreference quote is unclear. What happens is that if ANY memeber of the union defines ANY of those non-trivial special member functions, then ALL of them will be deleted by default in the union.

So since you have a non-trivial destructor for X, the U default constructor is deleted.

X is not a pod type because is not trivially copiable as it have destructor Also U is not a pod type.

U s2; try to call the default costructor that is deleted so the error

U s1 {}; use member wise initialization and don't call any costructor

In union with non pod member the default costructor of union is deleted because it would call the default costructor of members ie the compiler doesn't know which member to call the default costructor

 Union XX{
   string m1; 
   vector <int> m2;
}

default costructor of XX cannot call default costructor of m1 AND m2 so it is deleted

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