开发者

wstring in union

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


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)); }  
};


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜