如何解决C ++中的“ cppcoreguidelines-pro-type-cstyle-cast”错误?

时间:2019-11-04 13:19:30

标签: c++ visual-studio clang

我正在使用Visual Studio 2015 64位和Clang作为编译器的C ++。

我尝试使用以下代码将string转换为unsigned char*

string content = "some content from file";
unsigned char* m_Test = (unsigned char*)content.c_str();

但是,当我尝试构建项目时,这导致了错误:

  错误:不使用C样式强制转换在不相关的类型之间进行转换   [cppcoreguidelines-pro-type-cstyle-cast,警告为错误]

有什么想法可以解决吗?如果您能提供一些帮助,请非常感谢。

3 个答案:

答案 0 :(得分:1)

您有两个(或3个)选项:

1)用适当的C ++强制转换(static_castconst_castreinterpret_castdynamic_cast)替换C-style强制转换。

2)(更好的选择),找到一种方法,首先不需要进行强制转换就可以编写代码。

3)忽略/禁止警告(不是 I 的建议,尽管它是 的选择)。

答案 1 :(得分:1)

在现代C ++中,不应使用标准的cstyle强制转换,因为它们易于出错。为了能够从const char *的{​​{1}}方法返回的.c_str()进行投射。您需要对编译器有所了解。如此之多,就需要string。即使那样,您仍然需要保留常数。也可以将其丢弃。因此代码如下所示:

reinterpret_cast

string content = "some content from file"; const unsigned char* m_Test = reinterpret_cast<const unsigned char*>(content.c_str()); 只是告诉编译器“从现在开始,按规定处理此数据。”

答案 2 :(得分:0)

您可以对static_cast使用C ++强制转换方式:

编辑:正如评论中所指出的,对于您的特殊情况,您还需要一个const_cast

string content = "some content from file";
unsigned char* m_Test = static_cast<unsigned char*>(const_cast<char*>(content.c_str()));