正确的转换语法

时间:2018-08-16 16:49:24

标签: c++ casting

我有这样的代码:

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

在QtCreator中,我收到警告:

  

“使用旧式转换”。

我试图这样写:

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

但是我遇到另一个错误,无法在类型之间进行强制转换。

正确的语法应该是什么?

1 个答案:

答案 0 :(得分:7)

好的,这就是答案:

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