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

后端 未结 7 1777
逝去的感伤
逝去的感伤 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:00

    This will not work in C++ because you are returning a reference to a temporary which will be destroyed once the function is over. You need to create a new person on the heap and then return a reference to that.

提交回复
热议问题