Search code examples
c#c++pointersreferencedangling-pointer

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


C++ code:

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

C# code:

person NewPerson()
{
  return new person(); //return reference to person.
}

If I understand this right, the example in C++ is not OK, because the p will go out of scope, and the function will return a wild pointer (dangling pointer).

The example in C# is OK, because the anonymous new person will stay in scope as long as there is a reference to it. (The calling function gets one.)

Did I get this right?


Solution

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

    p is not a person, see most vexing parse. As such, you'd get a compiler error.

    For the rest, yes you're right.