i want to use string inside Union. if i write as below
union U
{
int i;
float f;
string s;
};
Compiler gives error saying U::S has copy constructor.
I read some other post for alternate ways for solving this issue. But i want to know why compiler doesn't allow this in the first place?
EDIT: @KennyTM: In any union, if member is initialized others will have garbage values, if none is initialized all will have garbage values. I think, tagged union just provides some comfort to access valid values from Union. Your question: how do you or the compiler write a copy constructor for the union above without extra information? sizeof(string) gives 4 bytes. Based on this, compiler can compare other members sizes and allocate largest allocation(4bytes in our example). Internal string length doesn't matter because it will be stored in a seperate location. Let the string be of any length. All that Union has to know is invoking string class copy constructor with string parameter. In whichever way compiler finds that copy constructor has to be invoked in normal case, similar method as to be followed even when string is inside Union. So i am thinking compiler could do like, allocate 4 bytes. Then if any string is assigned to s, then string class will take care of allocation and copying of that string using its own allocator. So there is no chance of memory corruption as well.
Is string not existed at the time of Union developement in compiler ? So the answer is not clear to me still. Am a new joinee in this site, if anything wrong, pls excuse me.