两个 static_cast 比 reinterpret_cast 好吗?

Is two static_cast better than reinterpret_cast?

我使用平面缓冲区,需要将数据写入文件。 Flatbuffer struct returns uint8_t*,但是std::ofstream::write接受char*作为参数。 你能告诉我哪种方法使用两个 static_casts 或 reinterpret_cast 更好吗?为什么?

    flatbuffers::FlatBufferBuilder fbBuilder // flatbuffer structer 
    ... // write something to fbBuilder
    std::ofstream out(filename);
    // this
    out.write(static_cast<const char*>(static_cast<const void*>(fbBuilder.GetBufferPointer())), fbBuilder.GetSize());
    // or this ? 
    out.write(reinterpret_cast<const char*>(fbBuilder.GetBufferPointer())), fbBuilder.GetSize());

在这种情况下,静态转换并没有增加安全性:来自 void* 的静态转换与重新解释转换同样危险。事实上,reinterpret cast 是根据通过 void* 的强制转换定义的,因此这些示例在语法上几乎完全相同。

这两个静态转换比单个重新解释转换更长且更难阅读。

static_cast等同于reinterpret_cast:

https://en.cppreference.com/w/cpp/language/reinterpret_cast

5) Any object pointer type T1* can be converted to another object pointer type cv T2*. This is exactly equivalent to static_cast< cv T2*> (static_cast< cv void*> (expression)) (which implies that if T2's alignment requirement is not stricter than T1's, the value of the pointer does not change and conversion of the resulting pointer back to its original type yields the original value). In any case, the resulting pointer may only be dereferenced safely if allowed by the type aliasing rules (see below)

在这种情况下使用 reinterpret_cast 是惯用的,例如 ostream::write() 的示例代码使用 reinterpret_cast:

https://en.cppreference.com/w/cpp/io/basic_ostream/write

#include <iostream>

int main()
{
    int n = 0x41424344;
    std::cout.write(reinterpret_cast<char*>(&n), sizeof n) << '\n';

    char c[]="This is sample text.";
    std::cout.write(c,4)<<'\n';
}

仅供参考,在此示例中您不需要强制转换为 constGetBufferPointer() returns 一个非常量 uint8_t*,你可以将一个非常量 char* 传递给 ostream::write()。指向非常量的指针可以分配给指向常量的指针,编译器将为您隐式应用 const。所以一次转换就足够了,在这种情况下需要 reinterpret_castuint8_t* 直接转换为 char*:

out.write(reinterpret_cast<char*>(fbBuilder.GetBufferPointer()), fbBuilder.GetSize());