Reputation: 332
Can anyone explain what's wrong with this implementation?
I am encountering following errors
error: a storage class on an anonymous aggregate in class scope is not allowed
error: use of deleted function ‘ResultUnion::ResultUnion()’
#include<iostream>
#include<vector>
using namespace std;
enum MediaKind { Container, Music};
typedef vector<string> StringList;
struct ResultUnion {
enum MediaKind kind;
static union {
struct {
string Type;
StringList List;
bool searchable;
}c;
struct {
string Type;
uint32_t duration;
}m;
};
};
int main()
{
ResultUnion ResultUnionobj[2];
ResultUnionobj[0].kind = Container;
ResultUnionobj[0].c.Type = "Container";
ResultUnionobj[1].kind = Music;
ResultUnionobj[1].m.Type = "Music";
cout << "first:" << ResultUnionobj[0].c.Type << endl << "second:" << ResultUnionobj[1].m.Type;
}
Upvotes: 0
Views: 148
Reputation: 411
Until C++11:
Unions cannot contain a non-static data member with a non-trivial special member function (copy constructor, copy-assignment operator, or destructor).
And since C++11:
If a union contains a non-static data member with a non-trivial special member function (copy/move constructor, copy/move assignment, or destructor), that function is deleted by default in the union and needs to be defined explicitly by the programmer.
If a union contains a non-static data member with a non-trivial default constructor, the default constructor of the union is deleted by default unless a variant member of the union has a default member initializer.
In short, string
in union is not a good idea.
Upvotes: 1