PDA

View Full Version : returning a string



mickey
27th January 2008, 22:33
Hello,
I have inside a method to manipulate a string large about 500 digits; I need to return it out; what's better? return it as reference parameter or as returned value? Or maybe keep it as member of the class?

thanks.

wysota
27th January 2008, 23:06
It depends whether you have to copy the data when you make a copy of the object. If not (like with QString), you can return by value. Otherwise a reference or a const reference would be advised. Keeping it as a class member won't change anything because at some point you have to access the member somehow - if you access it directly, it's like you'd return a reference. If the member is private, you'll be facing your original question again.

Thomas
3rd February 2008, 19:41
It depends whether you have to copy the data when you make a copy of the object. If not (like with QString), you can return by value. Otherwise a reference or a const reference would be advised. Keeping it as a class member won't change anything because at some point you have to access the member somehow - if you access it directly, it's like you'd return a reference. If the member is private, you'll be facing your original question again.

But do not forget that you should not return a reference to an object which is instanciated inside the method. As soon as the method is left, the object for which you returned the reference is destroyed and the reference becomes invalid.