c++ - Returning a reference parameter -
say have 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 return original string return astring; //or should return string(astring) }
i have situation need pass string function , if function fails task return string passed in.
my question i'm unsure on behaviour of returning astring
has been passed reference. should sort of code avoided, , if why? suprised return (does make copy perhaps?).
to on safe side constructed new object returned return string(astring)
again may overkill , not necessary.
any clarification appreciated.
thanks
yes, it's fine return astring
because return value, theoretically copy created (rvo can kick in, if does, doesn't affect behavior).
to on safe side constructed new object returned return string(astring) again may overkill , not necessary.
completely true. return astring;
fine.
Comments
Post a Comment