Bel*_*loc 0 c++ language-lawyer
A union can have member functions (including constructors and destructors), but it shall not have virtual ([class.virtual]) 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. [?Note: Absent default member initializers ([class.mem]), if any non-static data member of a union has a non-trivial default constructor ([class.default.ctor]), copy constructor, move constructor ([class.copy.ctor]), copy assignment operator, move assignment operator ([class.copy.assign]), or destructor ([class.dtor]), the corresponding member function of the union must be user-provided or it will be implicitly deleted ([dcl.fct.def.delete]) for the union. —?end note?]
In the code below clang emits the same error message irrespective of whether the data member U::i has a default member initializer or not. See demo.
#include <iostream>
struct S{
int j = 1;
S(const S&) {};
};
union U
{
int i = 1;
S s;
};
int main()
{
U u;
}
Run Code Online (Sandbox Code Playgroud)
Error message and note emitted by the compiler:
error: call to implicitly-deleted default constructor of 'U'
U u;
note: default constructor of 'U' is implicitly deleted because field 's' has no default constructor
S s;
Run Code Online (Sandbox Code Playgroud)
You're parsing the sentence incorrectly. The Absent default member initializers clause is stating that a union member with a non-trivial default constructor can be initialized by a default member initializer instead of having to provide a default constructor for the union.
It's not saying that providing a default member initializer for a different member is sufficient to avoid the constructor requirement, which seems to be how you've read it.
The following example is valid because of the clause you highlight
struct S{
int j = 1;
S(int) {};
};
union U
{
int i;
S s = 1;
};
int main()
{
U u;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74 次 |
| 最近记录: |