This has nothing to do with const_cast
. You are not trying to cast away const
-ness.
const MyStruct* my_struct = reinterpret_cast<const MyStruct* >(qbytearray.constData());
Frage
During the development of a Qt application for Embedded Linux (where improvements in performance are really welcomed), I came across the necessity to cast from a array of chars to a given struct. Till now, that was being done with the code:
MyStruct* const my_struct = reinterpret_cast< MyStruct* >(qbytearray.data());
while data()
being a member of the Qt class QByteArray
that transforms the byte array to a char*
. In doing this, tough, it makes a deep copy of the data, which is not good given the extra processing. Since I want to only read the data (the struct casted will never be used to edit), the alternative method QByteArray::constData()
is preferable, since it doesn't make a deep copy, but in contrast returns a const char*
instead of char*
.
The question is: how I should do the casting now? I tried to use const_cast without success.
MyStruct* const my_struct = const_cast< MyStruct* >(qbytearray.constData()); // compile error
const MyStruct* const my_struct = const_cast< MyStruct* >(qbytearray.constData()); // compile error
and reinterpret_cast
also didn't work because "it casts away the qualifiers", which is expected. The closest way I was capable of doing this was by first casting to char*
and later to the struct:
MyStruct* const my_struct = (MyStruct*)const_cast< char* >(qbytearray.constData());
but I get the feeling that not only this is "circle around" the problem, but also that the casting from char*
to MyStruct*
will ultimately sacrifice the processing improvement I was desiring.
So how do this casting correctly?
Lösung
This has nothing to do with const_cast
. You are not trying to cast away const
-ness.
const MyStruct* my_struct = reinterpret_cast<const MyStruct* >(qbytearray.constData());