Safe in C# not in C++, simple return of pointer / reference

后端 未结 7 1835
逝去的感伤
逝去的感伤 2021-01-19 22:46

C++ code:

person* NewPerson(void)
{
  person p;
  /* ... */
  return &p; //return pointer to person.
}

C# code:

person          


        
7条回答
  •  没有蜡笔的小新
    2021-01-19 23:19

    The scoping rules in this example are analogous but in C# if the returned value is assigned to something then it will not be garbage collected as long as something holds a reference to it. If it's not assigned to something, nothing holds a reference to it and it will be garbage collected next time the collector executes

提交回复
热议问题