c++ - 如何解决 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++ 中,不应使用标准 cstyle 类型转换,因为它们容易出错。能够从的方法const char *
返回。你需要对编译器很严格。这么多,这是需要的。即使这样,您也需要保持常量。这也可以扔掉。所以代码看起来像这样:.c_str()
string
reinterpret_cast
string content = "some content from file";
const unsigned char* m_Test = reinterpret_cast<const unsigned char*>(content.c_str());
reinterpret_cast
只是告诉编译器“从现在开始,按规定处理这些数据。”
推荐阅读
- blazor - Blazor - How to make child component show validation messages?
- c++ - 创建 GLFW 窗口失败?
- powershell - Powershell 工作流程,重启后继续
- python-3.x - 尝试在同一目录中打开文件时出现 FileNotFoundError
- python - Python:使用 Librosa 对第一个索引中的所有值进行数组索引
- excel - 如何将选择更改为整个工作表?
- javascript - 检测打印何时取消或未使用 Javascript
- python - 计算数据框中行的比例
- ansible - AWX 无法从 Ansible Galaxy 检索集合
- c# - C# QuikGraph 按 Graph Hiarachie 对元素进行排序