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?
The example in C++ is not ok because the 'p' will go out of scope, and the function will return an invalid pointer.
Correct.
The example in C# is ok because the anonymous 'new Person' will stay in scope as long there is any reference to it.
That is more or less correct but your terminology is not quite right. Scope in C# is the region of text in which an unqualified name can be used. The object here does not have a name. Lifetime is the period of runtime during which a storage location is guaranteed to be valid. Scope and lifetime are connected; when control leaves code associated with a scope, the lifetimes of locals declared within that scope are usually permitted to end. (There are situations where lifetimes of locals are longer or shorter than the time when control is in their scope though.)
Also, note that it is not any reference to the Person object that keeps it alive. The reference has to be rooted. You could have two Person objects that reference each other but are otherwise unreachable; the fact that each has a reference does not keep them alive; one of the references has to be rooted.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With