Where did variable = null as “object destroying” come from?

后端 未结 14 1837
无人共我
无人共我 2021-02-18 15:51

Working on a number of legacy systems written in various versions of .NET, across many different companies, I keep finding examples of the following pattern:

pub         


        
14条回答
  •  生来不讨喜
    2021-02-18 16:32

    It comes from C/C++ where doing a free()/delete on an already released pointer could result in a crash while releasing a NULL-pointer simply did nothing.

    This means that this construct (C++) will cause problems

    void foo()
    {
      myclass *mc = new myclass(); // lets assume you really need new here
      if (foo == bar)
      {
        delete mc;
      }
      delete mc;
    }
    

    while this will work

    void foo()
    {
      myclass *mc = new myclass(); // lets assume you really need new here
      if (foo == bar)
      {
        delete mc;
        mc = NULL;
      }
      delete mc;
    }
    

    Conclusion: IT's totally unneccessary in C#, Java and just about any other garbage-collecting language.

提交回复
热议问题