Reputation: 1460
Say I have the following code:
#include <string>
using namespace std;
string GetPath(const string & aString);
int main()
{
string dave = "hello";
string tom = GetPath(dave);
}
string GetPath(const string & aString)
{
//Do stuff
//If function fails then return original string
return aString;
//or should it be like this
return string(aString)
}
I have a situation where I need to pass a string into a function and if that function fails its task then I would like to simply return the string that was passed in.
My question is that I'm slightly unsure on the behaviour of just returning aString
as it has been passed by reference. Should this sort of code be avoided, and if so why? I was suprised that I could return it (does it make a copy perhaps?).
To be on the safe side I constructed a new object to be returned return string(aString)
but again this may be overkill and not necessary.
Any clarification would be greatly appreciated.
Thanks
Upvotes: 2
Views: 116
Reputation: 133
It seems to me that your main concern is that you're passing aString
to a function as a reference, and then returning that same reference in return aString
.
You're not doing that, your function returns by value, so if necessary will create a copy which is then returned.
I'd guess that you're thinking of references as being an equivalent of pointers, which they're not. Think of them more as an 'alias' of the original object, so if your return is by value, then a copy will be returned. If you returned const string &
then yes, you would return a reference to the original (hopefully unchanged) object.
Upvotes: 1
Reputation: 47762
return aString;
My question is that I'm slightly unsure on the behaviour of just returning aString as it has been passed by reference. Should this sort of code be avoided, and if so why?
No, that's just fine.
I was suprised that I could return it (does it make a copy perhaps?).
Yes, it does make a copy. (and it must make a copy in this case)
To be on the safe side I constructed a new object to be returned return string(aString) but again this may be overkill and not necessary
Yes, it would be an overkill. The compiler might, or might not optimize it to be exactly the same (through RVO).
Upvotes: 1
Reputation: 258618
Yes, it's fine to return aString
because you return by value, so theoretically a copy is created (RVO can kick in, but if it does, it doesn't affect behavior).
To be on the safe side I constructed a new object to be returned return string(aString) but again this may be overkill and not necessary.
Completely true. Just return aString;
is fine.
Upvotes: 2