C++: String and unions
I'm having a (design) problem:
I'm building an interpreter and I need some storage for variables. There are basically two types of content a variable here can have: string
or int
.
I'm using a simple class for the variables, all variables are then stored in a vector.
However, as a variable can hold a number or a string, I don't want C++ to allocate both and consume memory for no reason.
That's why I wanted to use unions:
union
{
string StringValue;
int IntValue;
}
However, strings don't work with unions.
- Is there any workaround so no me开发者_如何学Cmory gets eaten for no reason?
You may check out Boost.Variant
typedef boost::variant<std::string, int> Variable;
(Although that "wastes" extra memory - the size of a variant is something like the size of the largest type plus a word or so for bookkeeping - can't see how you could do with less anyway.)
However, as a variable can hold a number or a string, I don't want C++ to allocate both and consume memory for no reason.
Why not? How does four or eight or sixteen extra bytes hurt?
Unless you have a good reason, I don't think wasting 1KB is a lot.
If you want to use a union
with a string, you can instead use pointers. Either use string *, int
, string *, int *
, or const char *, int
or const char *, int *
, as the union member types.
I would not worry about the extra storage of a single integer. The overhead of correctly managing a variant or discriminated union with a string pointer is going to be much worse than using the extra storage associated with a single field.
精彩评论