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

前端 未结 11 669
不思量自难忘°
不思量自难忘° 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:30

    I would leave it alone. This might have been a deliberate choice as an old-fashioned version of the SafeNavigationOperator. As you say, in new code, I wouldn't recommend it, but for existing code, I'd leave it alone. If you do end up modifying it, I'd make sure that all calls to it are well-covered by tests.

    Edit to add: you could choose to remove it only in debug versions of your code via:

    CThingy *CLookupThingy::Lookup( name ) 
    {
    #if !defined(DEBUG)
       if (!this)
       {
          return NULL;
       }
    #endif
       // else do the lookup code...
    }
    

    Thus, it wouldn't break anything on production code, while giving you a chance to test it in debug mode.

提交回复
热议问题