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
Yes, it’s fine to return
aStringbecause you return by value, so theoretically a copy is created (RVO can kick in, but if it does, it doesn’t affect behavior).Completely true. Just
return aString;is fine.