views:

46

answers:

2

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?

+2  A: 

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
+1  A: 

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