Return By Reference

Were we talking about the C++ idiom...

  const std::string & ThisHereFunction();

I am interested in the implications of using it or not using it in the context of some C++ code which is going to be called from a "soft" layer such as ToolCommandLanguage (Tcl). -- JohnFletcher

It's bound to the lifetime of the containing object.

In my opinion, you are better off returning a reference counted object by value. This makes it easier to manage the storage associated. Of course, something like std::basic_string< CharT > is already reference counted, so this doesn't apply here. Also note that if you are programming with ConstCorrectness, you should have no problems with mutability when returning a constant reference object by value. For an example implementation, check out CppCountedPointerImplementation. There are many others, this one strives to be similar to std::auto_ptr<T> except for its exclusive, as opposed to shared, owner semantics. -- RobertDiFalco


Actually, the C++ standard does not require std::string to be reference counted. The strings are mutable, so it is jolly difficult to make a reference counted implementation be both correct and efficient, especially in a multi-threaded environment.

I thought about this problem a while back when SGI first introduced its rope classes based on just this argument. I decided there are a number of compromises that make this a workable situation. One does not have to abandon the performance provided by referenced counted, copy on write, strings. Of course, there is also the operator[] problem, but that can also be worked around. YMMV. -- RobertDiFalco


I think of this idiom as a performance optimization. IE: Client code should think of this function as if it were defined...

  std::string ThisHereFunction();

That is, a client can do this...
  std::string mystring = ThisHereFunction();
but should never do this...
  const std::string & mystring = ThisHereFunction();
By returning a const reference (and telling clients they should act as if you're just returning the string), you avoid the construction and destruction of one temporary object.

See PrematureOptimization.

Contributors: JeffGrigg


See LifetimeOfReturnedReference


CategoryCpp


EditText of this page (last edited April 22, 2002) or FindPage with title or text search