The suggestion about C++ is just to standardize the code (2)

Refer to Andrey Karpov's <<42 Suggestions for C++ Programming>>

11. The EOF check alone is not enough.

Sometimes the condition of'cin.eof()' is not enough. Consider adding the function call'cin.fail()' to the conditional expression.

template <typename T>
std::istream &operator >>(std::istream &i, sqlblob<T> &b) 
{
    
    
 ....
 while (!i.eof()) 
 {
    
    
 i >> tmp;
 buf+=(tmp+' ');
 }
 ....
}

Explanation: Using eof() to check the end of the file is not a sufficient condition, and you cannot be sure whether there is a read error or a stream error, both of which will cause specific problems. If there is any data reading error, it will cause an infinite loop, because eof() always returns false. This kind of loop may cause an endless loop. So we need to use bad(), fail() to query the flow status.

Suggestion: When using streams to read data, don't just use eof(), but also check for other faults. Use the bad() and fail() functions to check the status of the stream. The first function is used to stream integrity, and the second function is used to check data read errors. However, it is more convenient to use bool(), as shown in the correct code.

example:

template <typename T>
std::istream &operator >>(std::istream &i, sqlblob<T> &b) 
{
    
    
 ....
 while (i >> tmp) 
 {
    
    
 buf+=(tmp+' ');
 }
 ....
}

12. Automatically calculate the length of the string.

E.g:

else if (!strncmp(vstart, "HEX", 3))

After that, "BITLIST" was used instead of "HEX", but the programmer forgot to change 3 to 7. As a result, the string was not compared with "BITLIST", but only compared with "BIT". This error does not seem too serious, but it is a mistake after all.
modify:

else if (!strncmp(vstart, "BITLIST", strlen("BITLIST")))

It would be better to use strlen("BITLIST"),
but it has disadvantages:

  • There is no guarantee that the compiler will optimize the strlen() call: replace it with a constant.
  • You have to copy the string verbatim. It doesn't look good, and it can go wrong.
    In C++, we can use templates. Personally, I don’t like to use macros:
template<typename T, size_t N>
int mystrncmp(const T *a, const T (&b)[N])
{
    
    
 return _tcsnccmp(a, b, N - 1);
}

13. Learn to use Override and final identifiers.

Using these two identifiers is helpful for rewriting functions.

  • Override-indicates that the function is to override the virtual function in the base class.
  • Final-indicates that the function does not need to be rewritten in the derived class.
    example:
class CFrameWndEx : public CFrameWnd {
    
    
 ....
 virtual void WinHelp(DWORD_PTR dwData,
 UINT nCmd = HELP_CONTEXT) override;
 ....
};

14. Don't compare'this' with nullptr anymore.

According to modern C++ standards, this is never equal to nullptr.

15. Do not use NULL with nullptr.

Guess you like

Origin blog.csdn.net/weixin_45743162/article/details/109549496