【问题标题】:CppLint Cast Char* ErrorCppLint Cast Char* 错误
【发布时间】:2019-01-13 11:47:07
【问题描述】:

我在 CppLint 上遇到了这个错误:

Using C-style cast.  Use reinterpret_cast<xmlChar *>(...) instead  [readability/casting] [4]

当我尝试投射这样的东西时:

xmlChar* something = (xmlChar*) anOtherThing;

但如果我这样做:

xmlChar* something = reinterpret_cast<xmlChar *>(anOtherThing);

我在构建时遇到此错误:

error: reinterpret_cast from type ‘const char*’ to type ‘xmlChar*’ casts away constness

你能帮帮我吗?

【问题讨论】:

  • 好吧,将xmlChar* 替换为const xmlChar*。编译器告诉你你抛弃了常量
  • c 风格的演员表已被弃用,因为它们做的事情太多而且经常同时进行。通常 reinterpret_cast 是直接替换,并且您保持相同的类型。我看不出 xmlChar 是从哪里来的——那是 anOtherThing 的类型吗?所以我会写reinterpret_cast&lt;char*&gt;(anOtherThing)。但是如果你告诉我 anOtherThing 实际上是一个 const 指针,那么你还需要一个 const_castreinterpret_cast&lt;char*&gt;(const_cast&lt;Thing*&gt;(thing)),或者反过来: const_cast&lt;char*&gt;(reinterpret_cast&lt;const char*&gt;(thing));
  • 我建议你阅读这个great answer。它解释了你需要知道的关于 C++ 中的强制转换以及为什么你不应该使用 C-cast(做太多事情并且可以隐藏 UB)
  • 感谢您的帮助,很好:)

标签: c++ char cpplint


【解决方案1】:

所以解决方案是像 Vivick 说的那样用 const xmlChar* 替换 xmlChar*。

但是如果我们像我一样使用 xmlChar*,我们可以使用函数 xmlChartStrdup() 而不是 reinterpret(),它避免了将所有代码更改为 const。

谢谢大家

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多