首页 > 解决方案 > 如何解决 C++ 中的“cppcoreguidelines-pro-type-cstyle-cast”错误?

问题描述

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

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

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

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

错误:不要使用 C 样式转换在不相关的类型之间进行转换 [cppcoreguidelines-pro-type-cstyle-cast,-warnings-as-errors]

知道如何解决它吗?如果您能有所启发,我将不胜感激。

标签: c++visual-studioclang

解决方案


在现代 C++ 中,不应使用标准 cstyle 类型转换,因为它们容易出错。能够从的方法const char *返回。你需要对编译器很严格。这么多,这是需要的。即使这样,您也需要保持常量。这也可以扔掉。所以代码看起来像这样:.c_str()stringreinterpret_cast

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

reinterpret_cast只是告诉编译器“从现在开始,按规定处理这些数据。”


推荐阅读