Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reinterpret_cast casts away qualifiers

I add an issue on reinterpreting a variable and I don't know why..

int ProgressBar(const uint64_t data_sent, const uint64_t data_total, void const *const data) {     Dialog *dialog = reinterpret_cast<Dialog*> (data);     dialog->setValue((data_sent *100) / data_total); } 

the reinterpret_cast seems not allowed and say

reinterpret_cast from 'const void *) to Dialog * casts away qualifiers

Any idea

like image 963
Seb Avatar asked Jan 17 '15 02:01

Seb


People also ask

When should I use Reinterpret_cast?

Purpose for using reinterpret_cast It is used when we want to work with bits. If we use this type of cast then it becomes a non-portable product. So, it is suggested not to use this concept unless required. It is only used to typecast any pointer to its original type.

What is the difference between Static_cast Dynamic_cast Const_cast and Reinterpret_cast?

Use static_cast as the equivalent of a C-style cast that does value conversion, or when we need to explicitly up-cast a pointer from a class to its superclass. Use const_cast to remove the const qualifier. Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types.

Is Reinterpret_cast safe?

the result of a pointer-to-pointer reinterpret_cast operation can't safely be used for anything other than being cast back to the original pointer type.

Is reinterpret cast the same as C-style cast?

C-style casts are quite similar to reinterpret_cast s, but they have much less syntax and are not recommended. The thinking goes that casting is inherently an ugly operation and it requires ugly syntax to inform the programmer that something dubious is happening.


2 Answers

As Nick Strupat stated in comment,

reinterpret_cast can't cast away cv-qualifiers

So you can use reinterpret_cast and const_cast together.

Dialog *dialog = const_cast<Dialog*>(reinterpret_cast<const Dialog *>(data)); 
like image 68
Pranit Kothari Avatar answered Sep 19 '22 18:09

Pranit Kothari


You need to also use a const_cast to remove const qualifiers. Also, casting from void * can use static_cast, it does not need to reinterpret. For example:

Dialog const *dialog = static_cast<Dialog const *>(data); Dialog *d2 = const_cast<Dialog *>(dialog); 

However , make sure that the Dialog is actually not a const object; attempting to modify a const object (presumably setValue does this) causes undefined behaviour.

I'd suggest rethinking the interface to ProgressBar to avoid needing this cast.

like image 37
M.M Avatar answered Sep 21 '22 18:09

M.M