2015-09-26 25 views
1

我希望静态分析器在下面的代码中警告我关于无效右值解引用。如何在clang或cppcheck中执行该操作?如何检查cppcheck或clang中的类型安全?

#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; 
} 
+0

这与类型安全无关。 –

回答

4

我是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代码也有很好的警告。

如果您有兴趣,请随时与我们联系。