Differences between revisions 2 and 3
Revision 2 as of 2006-10-19 10:08:04
Size: 895
Editor: dbws1bcx04
Revision 3 as of 2009-09-20 23:51:28
Size: 895
Editor: localhost
Comment: converted to 1.6 markup
No differences found!

MIGRATED to http://cwiki.apache.org/confluence/display/qpid/ReturnStdStringByValue

Don't do this:

  std::string& f();
  const std::string& g(); // Not much better

Instead do this:

  std::string f();
  std::string g();

std::string is designed expressly to allow you to treat strings as simple pass-by-value types, like int. It's efficient to return by value rather than reference and it avoids core dumps if the real string hidden away in f gets deleted before the reference. In particular it allows f() to compute once-off values and forget about them, e.g.:

std::string hello(const std::string& name) { return "hello " + name; }

With the "&" style return this would be an immediate disaster as the returned reference is invalid before the caller even gets it! NB. The last example contains another error! See CppTips/BewareOfStringPromotion.

CppTips/ReturnStdStringByValue (last edited 2009-09-20 23:51:28 by localhost)