Looking at the following function:
std::string& foo (std::string& s)
{
s.erase(0.s.find_first_not_of(" \f\t\v\r\n");
return s;
}
When one passes in a string, it does modify the original string right? Why would you want to return the modified string when you are also modifying the original?
Trying to better understand why someone might have coded this function this way? Well someone did do this so I am being asked why am I only doing the following:
std::string mystring = " This is cool";
foo(mystring);
std::cout << mystring << std::endl;
and why I am not making use of the returned value?
When one passes in a string, it does modify the original string right?
That is correct.
Trying to better understand why someone might have coded this function this way?
It allows chaining of function calls.
In your case, you can use:
std::cout << foo(mystring) << std::endl;
An example of chaining of function calls is how operator<< is used with std::cout. The operator<< functions return a reference to the ostream. Because of that, you are able to use:
std::cout << foo(mystring) << std::endl;
Otherwise, you would be forced to use:
std::cout << foo(mystring);
std::cout << std::endl;
why I am not making use of the returned value.
The language does not force you to use the returned value. However, you can use it, as shown above.
When one passes in a string, it does modify the original string right?
Correct. Since it is a reference it modifies the the object from the caller.
Why would you want to return the modified string when you are also modifying the original?
Well, if you wanted to chain the calls together then you need to return the object by reference. If you didn't you couldn't use
foo(foo(foo(some_string)));
and why I am not making use of the returned value?
It's unclear why they aren't using the function return value but you don't have to. It is perfectly legal to discard the return value. One thing to note is the inverse is not okay. If you declare a function returns something, and you don't, then that is undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With