【发布时间】:2011-02-19 21:57:46
【问题描述】:
我在 std::string 中有一个我需要的 unsigned char 数组,但我目前的方式使用我想避免的 reinterpret_cast。有没有更清洁的方法来做到这一点?
unsigned char my_txt[] = {
0x52, 0x5f, 0x73, 0x68, 0x7e, 0x29, 0x33, 0x74, 0x74, 0x73, 0x72, 0x55
}
unsigned int my_txt_len = 12;
std::string my_std_string(reinterpret_cast<const char *>(my_txt), my_txt_len);
【问题讨论】:
-
你为什么不喜欢
reinterpret_cast...? -
强制强制转换似乎总是一种技巧,我宁愿按原样使用东西,而不是强迫编译器将它们视为其他东西。
-
为什么不使用
char代替my_txt;毕竟,您发布的那些值是 ASCII。这可能会导致解决其他问题。 -
这是一个生成的文件,所以我宁愿不必进一步处理它。
-
从
unsigned char*初始化string对我来说似乎很合理。我很惊讶有人反对在不使用演员表的情况下这样做。
标签: c++ stdstring reinterpret-cast