首页 > 解决方案 > 正确的转换语法

问题描述

我有这样的代码:

const quint8* data[2];    
const float *p0 = (float*)data[0]

在 QtCreator 中,我收到警告:

“使用旧式演员表”。

我试着这样写:

const float *p0 = const_cast<float*>(data[0])

但是我遇到了另一个无法在类型之间转换的错误。

正确的语法应该是什么?

标签: c++casting

解决方案


好的,这就是答案:

const float *p0 = reinterpret_cast<const float*>(data[0]);

要非常小心 C++ 严格的别名规则。它们对您的示例的含义是,您可以通过p0 当且仅当 data[0]指向浮动对象时合法访问。例如

这是合法的

const float f = 24.11f;

const quint8* data[2] {};

data[0] = reinterpret_cast<const quint8*>(&f);
// for the above line:
// data[0] can legally alias an object of type float
//    if quint8 is typedef for a char type (which is highly likely it is)
// data[0] now points to a float object

const float *p0 = reinterpret_cast<const float*>(data[0]);
// p0 points to the float object f. Legal

float r = *p0; // legal because of the above

return r;

这是非法的:

const quint8 memory[4]{};
memory[0] = /* ... */;
memory[1] = /* ... */;
memory[2] = /* ... */;
memory[3] = /* ... */;

const quint8* data[2] {};

data[0] = memory;
// data[0] doesn't point to a float object

const float *p0 = reinterpret_cast<const float*>(data[0]);
// no matter what trickery you use to get the cast
// it is illegal for a `float*` pointer to alias a `quint8[]` object

float r = *p0; // *p0 is illegal and causes your program to have Undefined Behavior

推荐阅读