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

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

    It may not crash in most compilers since non-virtual functions are typically either inlined or translated into non-member functions taking "this" as a parameter. However, the standard specifically says that calling a non-static member function outside the lifetime of the object is undefined, and the lifetime of an object is defined as beginning when memory for the object has been allocated and the constructor has completed, if it has non-trivial initialization.

    The standard only makes an exception to this rule for calls made by the object itself during construction or destruction, but even then one must be careful because the behavior of virtual calls can differ from the behavior during the object's lifetime.

    TL:DR: I'd kill it with fire, even if it will take a long time to clean up all the call sites.

提交回复
热议问题