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

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

C++ code:

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

C# code:

person          


        
相关标签:
7条回答
  • In C++, that 'p' will live on the stack and thus get clobbered when the function returns. In C#, the garbage collector knows to not clobber it until the last reference is lost.

    ('clobber' being used loosely here... :p)

    0 讨论(0)
提交回复
热议问题