【问题标题】:error: invalid conversion from 'unsigned char*' to 'const signed char*'错误:从 'unsigned char*' 到 'const signed char*' 的无效转换
【发布时间】:2016-09-30 15:31:54
【问题描述】:
uint8_t* buf1;
...
const signed char* buf2 = static_cast<const signed char*>(buf1);

从类型 'uint8_t* {aka unsigned char*}' 到类型的无效 static_cast 'const 有符号字符*'

c-style-cast: (const signed char*) 工作正常

在这种情况下使用 c-style-cast 与 static_cast 有什么危险吗?

【问题讨论】:

  • 好吧,定义“危险”。它合法的。
  • static_cast 错误提示这不是安全操作,为什么 static_cast 失败?
  • 因为你需要reinterpret_cast
  • No static_cast 告诉你它不能投射它,并不是说投射它很危险,你需要在这里使用reinterpret_cast,它会失败,因为签名和未签名的字符不同类型
  • 因为static_cast 不能在指向不同类型的指针之间进行转换(除了void*)。您可以为此使用reinterpret_cast。操作是否安全取决于输入来自何处以及您正在使用它做什么。从语言的角度来看,这当然是合法的。

标签: c++ c++11 casting


【解决方案1】:

在这种情况下使用 c-style-cast 与 static_cast 有什么危险吗?

正如错误消息所解释的那样,在这种情况下,static_cast 根本不是一个选项。

使用 c-style cast 的危险在于您可能不打算执行 reinterpret_cast,这正是 c-style cast 在这里执行的操作。如果您打算执行 reinterpret_cast,请使用 reinterpret_cast。如果你打算使用static_cast,那么你的逻辑是错误的,因为类型与static_cast不兼容。

【讨论】:

    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2018-03-24
    • 1970-01-01
    相关资源
    最近更新 更多