Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error converting a const void* to some other pointer without const_cast

The function

int compare(const void* a, const void* b)
{
    SomeDataType g1 = *(static_cast<SomeDataType*>(a));
    SomeDataType g2 = *(static_cast<SomeDataType*>(b));
    g1.firstelement < g2.firstelement ? 1 : -1;
}

This code returns an error saying "static cast can't cast from const void* to SomeDataType*." I use const_cast like

SomeDataType g1 = *(static_cast<SomeDataType*>(const_cast<void*>(a))) ; 

to get this working. Is that a right way to do it ? Or am I missing something? I am not understanding quite how this works.

like image 514
navderm Avatar asked May 24 '26 17:05

navderm


2 Answers

It doesn't feel right because it shouldn't feel right. Someone gave you a pointer and in the interface you promised that you would not modify it, casting away the const is breaking your promise (well, not really, but the type system considers that if you cast away const, is is because you want to modify the object, which would break your promise).

I suggest that you don't drop the const:

int compare(const void* a, const void* b)
{
    SomeDataType g1 = *(static_cast<const SomeDataType*>(a));
    SomeDataType g2 = *(static_cast<const SomeDataType*>(b));
    return g1.firstelement < g2.firstelement ? 1 : -1;
}
like image 65
David Rodríguez - dribeas Avatar answered May 26 '26 07:05

David Rodríguez - dribeas


Do this:

const SomeDataType g1 = *static_cast<const SomeDataType *> (a);
const SomeDataType g2 = *static_cast<const SomeDataType *> (b);

You don't need const_cast here.

However I prefer this:

int compare(const SomeDataType &g1, const SomeDataType &g2)
{
    return g1.firstelement < g2.firstelement ? 1 : -1;
}
like image 35
masoud Avatar answered May 26 '26 06:05

masoud