Hacker News new | ask | show | jobs
by joosters 4575 days ago
I thought that the issue is the const-ness of the variables, and nothing to do with casting void* ->sometype*

Essentially, they are making use of const pointers to ensure that the code doesn't change the data. (gcc would throw a warning if you did). BUT: the problem comes when you want to free() the data. A strict interpretation of C would be that you can't free() something that's const, because it clearly is altering the data. However, you have to free the data sometime or other...

A possible workaround is to write a freeconst() macro that does the cast to void* and calls free(), and wrap this macro in the 'temporarily disable this warning #pragma'. This way, you only need to turn off the warning in one place in your code.

2 comments

The BSD solution to this problem is __DECONST(), a macro which basically casts through `uintptr_t`.

    #define __DECONST(type, var)   ((type)(uintptr_t)(const void*)(var))
On a related note, if you're using new and delete you can simply delete a pointer-to-const without jumping through any const_cast hoops, though I often wish I had a way of blocking that for APIs where the callee doesn't take ownership of a const Foo*.
Is that actually a standard though? ISTR some compilers complaining if you use delete with a const pointer (sorry, this is from ages ago, I cannot recall which compiler...)

You can make a fair argument that using delete with a const pointer is a type error, after all the data can hardly be considered const if it has just been eradicated...