Ways to handle the lifetime of a returned reference in C++
- Don't worry about it (only an option if you like segment faults)
- The caller must not use the returned reference after its defined lifetime. Typically, the lifetime of a returned reference is implicitly defined to be the lifetime of the object that returned the reference. If otherwise, the method must explicitly state the lifetime of the returned reference is in its comments ("this reference is valid until the next call to a non-const method of this object").
- Return a reference-counted pointer instead, or an AutoPtr, so that the returned reference will automatically be valid for as long as the caller holds onto it.
- Use ReturnByValue instead, making sure that the returned object has ValueSemantics.
- Return pointers to heap objects instead, and use GarbageCollectionInCpp.
CategoryCpp