4 ms·
I find it awesome that you can do that, the extra flexibility is great, e.g. when you're working with const char* arrays, sometimes, you need to create a copy o
by klingonopera 7y ago
I find it awesome that you can do that, the extra flexibility is great, e.g. when you're working with const char* arrays, sometimes, you need to create a copy of that char array, but save its pointer (char* ) in a (const char* ) variable, but you're still going to need to delete that copy later... and then you're glad that you can simply recast a (const char* ) into (char* ).
I save the data of whether or not it's a copy into a flag variable, so my program knows when and when not to delete a const char* .
The alternative would be of course to create a two variables, one char* and one const char* , but that would double the memory needed, but only one type of variable would be used at a time.
- account42 7y agoCouldn't you use a union for that? class string { union { const char *referenced; char *copied; } data; bool copied; public: string(const char *source, booly copy) { if(copy) { data.copied = strdup(source); copied = true; } else { data.referenced = source; copied = false; } } operator const char *() const { return copied ? data.copied : data.referenced; } ~string() { if(copied) { free(data.copied); } } }; No const_cast and no wasted memory and it's clear that you are storing two semantically different types. I would expect the conversion operator to optimize down to a noop since in all cases the returned address is equal to this.
- klingonopera 7y agoYes, that could work too, but in my opinion, only unnecessarily complicates things. I want the pointer (actually, that to what it's pointing to) to be referenced as const in all cases, except when I create a copy or delete that copy, in which case I then explicitly recast them as not-const. That's just two tiny exceptions in code I have to write anyways. Such as it is, I would only consider a union of them if I'd actually need const/non-const 50/50 of the time, but my current use case is more like 98/2. Apart from that, I'm guessing you're from a C++ background, as there are no classes in C? (and also, if you use C++, it's recommended to use "delete" instead of "free", since the latter is a C function) EDIT: Actually, it's only one exception/re-cast, when I delete it, as no compiler would complain about saving a char* in a const char* data type.