C++ reinterpret_cast 抛弃限定词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27995692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
reinterpret_cast casts away qualifiers
提问by Seb
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
似乎不允许,说
reinterpret_cast from 'const void *) to Dialog * casts away qualifiers
reinterpret_cast 从 'const void *) 到 Dialog * 抛弃限定符
Any idea
任何的想法
回答by Pranit Kothari
As Nick Strupat stated in comment,
正如 Nick Strupat 在评论中所说,
reinterpret_cast can't cast away cv-qualifiers
reinterpret_cast 不能抛弃 cv 限定符
So you can use reinterpret_cast
and const_cast
together.
所以你可以reinterpret_cast
和const_cast
一起使用。
Dialog *dialog = const_cast<Dialog*>(reinterpret_cast<const Dialog *>(data));
回答by M.M
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:
您还需要使用 aconst_cast
来删除const
限定符。此外,从void *
可以使用的铸造static_cast
,它不需要重新解释。例如:
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.
但是,请确保 Dialog 实际上不是const
对象;尝试修改 const 对象(大概setValue
是这样做的)会导致未定义的行为。
I'd suggest rethinking the interface to ProgressBar
to avoid needing this cast.
我建议重新考虑界面ProgressBar
以避免需要此演员表。