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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:54:05  来源:igfitidea点击:

reinterpret_cast casts away qualifiers

c++reinterpret-cast

提问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_castseems 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_castand const_casttogether.

所以你可以reinterpret_castconst_cast一起使用。

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

回答by M.M

You need to also use a const_castto remove constqualifiers. 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 constobject; attempting to modify a const object (presumably setValuedoes this) causes undefined behaviour.

但是,请确保 Dialog 实际上不是const对象;尝试修改 const 对象(大概setValue是这样做的)会导致未定义的行为。

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

我建议重新考虑界面ProgressBar以避免需要此演员表。