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

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

C++ code:

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

C# code:

person          


        
7条回答
  •  旧时难觅i
    2021-01-19 23:10

    Yes, you got it right.

    However, in C++ you would really do like this

    person NewPerson()
    {
      person p;
      /* ... */
      return p; //return person.
    }
    

    and be pretty sure that in a call

    person x = NewPerson();
    

    the compiler will optimize out the copying of the return value.

提交回复
热议问题