This is basically a tagged union:
#include <string>
using std::string;
struct test{
test():tag(INT),i(0){};
test(const test&)=delete;
test& operator=(const test&)=delete;
enum {STRING,INT} tag;
union {
string s;
int i;
};
test& operator=(string s){
this->s=s;
tag=STRING;
return *this;
}
test& operator=(int i){
this->i=i;
tag=INT;
return *this;
}
~test(){
if (tag==STRING)
s.~string();
}
};
int main(){
test instance;
instance="string";
return 0;
}
It compiles but every time it crashes with a Segmentation fault. I'm just out of curiosity it's a pretty complete union class, provided a custom destructor, no move and no copy, then why will this crash? Must I use a string*
in a union? If so, why?