tags:

views:

83

answers:

2

Hi,
I'd like to define a union, for reading special kind of binary files. The union should have two members one of int and the other a kind of string, or any other that's the question; what is the best way to do this?

union uu {  
    int intval;  
    wstring strval;  

    uu(){ memset(this, 0, sizeof(this)); }  
}

it says: "Member strval of union has copy constructor" I think strval should have a * or a &; how would you define it?

thanks in advance
Oops

+8  A: 

You can't do it. Members of unions must be POD types - i.e. they must not have constructors or destructors. And even if you could, your call to memset would trample all over the string, leading to undefined behaviour. You can of course use a pointer:

union uu {  
    int intval;  
    wstring * strval;  

    uu(){ memset(this, 0, sizeof(uu)); }  
};
anon
Though the null pointer isn't necessarily all 0's. So that constructor is still incorrect.
GMan
For completeness, you should mention that he needs to assign something to the pointer. So it's like `u.strval = new wstring("foo")` and he needs to `delete` that memory afterwards.
Johannes Schaub - litb
C++0x adds the ability to store non-POD types in unions. But for now, it's POD-types only.
jalf
+4  A: 

boost.variant is what you want to use

boost::variant<int, wstring> v("hello");

If you use a pointer as member of the union, you have to allocate and free the string that the pointer points to yourself, preferably using new and delete.

boost::variant solves that problem: It allocates all members within the variant object itself (so no dynamic allocation for storing members), and you don't have to do any new or delete call yourself at all.

Johannes Schaub - litb