What's the reasoning behind putting constants in if statements first?

前端 未结 8 2067
孤城傲影
孤城傲影 2021-02-03 16:53

I was looking at some example C++ code for a hardware interface I\'m working with and noticed a lot of statements along the following lines:

if ( NULL == pMsg )          


        
8条回答
  •  一向
    一向 (楼主)
    2021-02-03 17:23

    To clarify what I wrote in some of the comments, here is a reason not to do this in C++ code.

    Someone writes, say, a string class and decides to add a cast operator to const char*:

    class BadString
    {
    public:
       BadString(const char* s) : mStr(s) { }
    
       operator const char*() const { return mStr.c_str(); }
    
       bool operator==(const BadString& s) { return mStr == s.mStr; }
    
       // Other stuff...
    
    private:
       std::string mStr;
    };
    

    Now someone blindly applies the constant == variable "defensive" programming pattern:

    BadString s("foo");
    
    if ("foo" == s) // Oops.  This compares pointers and is never true.
    {
       // ...
    }
    

    This is, IMO, a more insidious problem than accidental assignment because you can't tell from the call site that anything is obviously wrong.

    Of course, the real lessons are:

    1. Don't write your own string classes.
    2. Avoid implicit cast operators, especially when doing (1).

    But sometimes you're dealing with third-party APIs you can't control. For example, the _bstr_t string class common in Windows COM programming suffers from this flaw.

提交回复
热议问题