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?
Asked
Active
Viewed 288 times
2 Answers
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