1. 程式人生 > >你需要的代碼靜態檢查

你需要的代碼靜態檢查

should pan 是你 eval 等於 可能 應該 rev c++

使用cppcheck給工程代碼做靜態檢查,主要發現了以下幾個問題:

1.使用C風格的類型轉換

警告如下:

C-style pointer casting detected. C++ offers four different kinds of casts as replacements: static_cast, const_cast, dynamic_cast and reinterpret_cast. A C-style cast could evaluate to any of those automatically, thus it is considered safer if the programmer explicitly states which kind of cast is expected. See also: https://www.securecoding.cert.org/confluence/display/cplusplus/EXP05-CPP.+Do+not+use+C-style+casts.

應該使用C++提供的static_cast, const_cast, dynamic_cast 和 reinterpret_cast 做類型轉換,明確轉換的類型。

2.叠代器使用後置疊加(疊減)運算符

警告如下:

Prefix ++/-- operators should be preferred for non-primitive types. Pre-increment/decrement can be more efficient than post-increment/decrement. Post-increment/decrement usually involves keeping a copy of the previous value around and adds a little extra code.

叠代器前置++和後置++ 的運行效率是不同的,前置++效率更高,因為後置運算符需要做一個臨時的類對象拷貝。

3. 直接在函數參數中使用C風格字符串。

警告如下:

The conversion from const char* as returned by c_str() to std::string creates an unnecessary string copy. Solve that by directly passing the string.

比如一個函數的參數類型是strng,調用時實參直接使用了C風格的字符串,於是就會有以上提示,主要還是因為這裏會造成一個不必要的字符串拷貝,降低運行效率。

4. 使用無用的find

很多時候,我們會寫下面的find代碼,值不等於-1則說明找到了該字符串,

if(std::string::npos != dataStr.find("what"))
    //do something

該代碼段會導致報警:

Either inefficient or wrong usage of string::find(). string::compare() will be faster if string::find‘s result is compared with 0, because it will not scan the whole string. If your intention is to check that there are no findings in the string, you should compare with std::string::npos.

代碼本身不會出錯,但是效率上是不被認可的,如cppcheck所說,如果你希望檢查某個字符串是不是某個期望的字符串,那你應該使用compare函數,因為這樣更快。

5. 函數參數使用傳值而不是傳引用

警告如下:

Parameter ‘strShowTime‘ is passed by value. It could be passed as a const reference which is usually faster and recommended in C++.

C++給了引用傳參,而你不使用,那就是你的問題了。

6. 構造函數沒有使用初始化成員變量列表,而是習慣於寫入構造函數體

警告有:

Member variable ‘CActiveComboItemXml::m_phorActivecombo‘ is not initialized in the constructor.

或者如:

When an object of a class is created, the constructors of all member variables are called consecutively in the order the variables are declared, even if you don‘t explicitly write them to the initialization list. You could avoid assigning ‘m_strHrefOnPanReady‘ a value by passing the value to the constructor in the initialization list.

這個問題很普遍,因為很多程序員不習慣在構造函數的初始化列表中初始化成員變量,有的是直接忽略掉,有的則是在構造函數的函數體中去使用賦值運算符賦值,可是這個時候已經不是初始化了,而是賦值階段了。這是個很危險的習慣!

這幾個問題大量出現在cppcheck的問題列表中,是我們經常犯的編程問題,應從代碼風格上進行規避。
當然了,可能的錯誤(警告)是由不當的編碼風格和不紮實的C++編碼基礎導致的,通過靜態檢查我們自己的代碼,可以最大層度的寫出易讀且不容易出錯的代碼。

推薦大家使用cppcheck!

你需要的代碼靜態檢查