1

I have a function defined a local variable typed in CStringW, is it safe to return this object to the caller by value, not by reference?

dan04
  • 87,747
  • 23
  • 163
  • 198
Thomson
  • 20,586
  • 28
  • 90
  • 134
  • The converse is actually what's not safe; don't return a reference to a local variable because when it gets out of scope your reference is dead. – GManNickG Aug 10 '10 at 02:57

2 Answers2

2

Yes, it should be ok. CString internally uses a buffer with reference counting and does copy-on-write, so that when you create a copy of CString and then destroy the original object, everything should "just work".

Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
1

I believe CString is from MFC, not STL, so you might want to change your tags.

If you're returning a local variable from a function, it's safe to return by value, but not safe to return by reference. Returning by value effectively copies the string to the caller. Returning by reference gives the caller a reference to the local variable which is destroyed when the function returns - so the caller can never use it, and the returned reference is always invalid.

AshleysBrain
  • 22,335
  • 15
  • 88
  • 124