gpt4 book ai didi

c++ - 如何检查 cppcheck 或 clang 中的类型安全?

转载 作者:行者123 更新时间:2023-11-30 01:46:41 24 4
gpt4 key购买 nike

我希望静态分析器警告我以下代码中的无效右值取消引用。我如何在 clang 或 cppcheck 中做到这一点?

#include <memory>

using namespace std;

unique_ptr<int> myfunc(void)
{
unique_ptr<int> a(new int(2));
return a;
}


int main()
{
const int& ra = *myfunc();
return 0;
}

最佳答案

我是 Cppcheck 开发人员。

Cppcheck 有一个相关的 std::string 检查器。例如,您收到此代码的 Cppcheck 警告:

std::string hello();

unsigned int f() {
const char *p = hello().c_str();
return 0;
}

你得到的警告是:

[2.cpp:4]: (error) Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.

报是因为返回的std::string对象被立即删除了。在初始化之后的任何地方取消引用指针 p 都是 UB。

我认为如果您的 unique_ptr 代码也有警告会很棒。

如果您有兴趣.. 请随时帮助我们。

关于c++ - 如何检查 cppcheck 或 clang 中的类型安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com