Return by copy
I am having difficulty understanding how this situation will work.
using std::string;
//Prototypes
string MixCase(string& sString);
void UseRef (string& sRefString);
void UseCopy(string sCopyString);
void main(int argc, char** argv)
{
string MyString;
UseRef (MixCase(MyString));
UseCopy(MixCase(MyString));
}
string MixCase(string& sString)
{
string sTempString;
...
return sTempString;
}
string UseRef(string& sRefString)
{
//Will sRefString be valid when it comes from MixCase ???
}
string UseCopy(string sCopyString)
{
//This should work just fine
}
I am trying to convert Delphi (pascal) code to C++. The Delphi code that I am converting does this type of stuff all the time.
Any comments are welcome.
Thanks in advance.
Kendall
[961 byte] By [
kenrus] at [2007-11-20 11:48:01]

# 1 Re: Return by copy
References are fun, if you're new to C++ it is the first thing I would suggest you master. There are plenty of tutorials around the internet that will help you out.
As for your question, the function MixCase takes a reference to a string and returns a string. The code you've copied doesn't modify the input string sString and therefore sString will remail the same as when you called the function.
If you want the input string MyString to be modified by the function MixCase then modify sString within the function. UseRef will have a valid string sRefString, however it will not have anything to do with the input string MyString.
What are you trying to achieve with this code exactly?
# 2 Re: Return by copy
I apologize, I realize now that I wasn't very specific with my question.
What I meant to ask is in regards to this line:
UseRef (MixCase(MyString));
MixCase() is returning a copy, which is then immediately passed as a reference to UseRef().
When does this returned copy go out of scope. Will it still be valid inside the UseRef() function ?
# 3 Re: Return by copy
You should get a compilation error, because the argument to UseRef is a reference to non-const. By using MixCase() directly as the argument, that means that you are trying to pass a temporary to a ref-to-non-const, which is not allowed.
To answer the question (and assuming you change the arg to UseCase to "const string&"), then the temporary lasts as long as it's needed - basically to the sequence point (the semi-colon in this case), which includes the invocation of the function. So, yes, it will be valid inside the UseRef function.
# 4 Re: Return by copy
I don't get a compilation error, but then again I am using Microsoft Visual C++ 6.0 which I understand is quite old.
I had verified that it worked through testing, but I had just never seen C++ code that used a temporary like that so I wasn't sure. However, the Delphi code that I am translating/porting uses that all the time.
example: func1(func2(func3(func4())));
Thanks for the help!
Kendall