How bad is “if (!this)” in a C++ member function?

前端 未结 11 671
不思量自难忘°
不思量自难忘° 2021-02-04 23:16

If I come across old code that does if (!this) return; in an app, how severe a risk is this? Is it a dangerous ticking time bomb that requires an immediate app-wide

11条回答
  •  悲&欢浪女
    2021-02-04 23:48

    You can safely fix this today by returning a failed lookup object.

    class CLookupThingy: public Interface {
      // ...
    }
    
    class CFailedLookupThingy: public Interface {
     public:
      CThingy* Lookup(string const& name) {
        return NULL;
      }
      operator bool() const { return false; }  // So that GetLookup() can be tested in a condition.
    } failed_lookup;
    
    Interface *GetLookup() {
      if (notReady())
        return &failed_lookup;
      // else etc...
    }
    

    This code still works:

    CThingy *pFoo = GetLookup()->Lookup( "foo" ); // will set pFoo to NULL without crashing
    

提交回复
热议问题