C++ returning a string reference and passing a string reference in the same function

arguments, c++, return-type

Solution

The original function looks like an ugly hack. It certainly invokes a "WTF" from anyone reading the code, and as such it should probably be avoided.

Note that your replacement relies on `somevalue` being a global object or similar. If that's not the case (i.e. if `somevalue` is computed inside the function), you'd be returning a dangling reference - buggy code.

I'd say the cleanest way would be to get rid of one-liner-enabling hacks, rely on move semantics and/or [N]RVO to do their job, and just return by value:

std::string GetCurrentDataSourceName()
{
   return somevalue;
}

Problem

I have been arguing with my superior about this function: ``` const std::string &GetCurrentDataSourceName(std::string & sName) { sName = GetAnotherComponent().GetName(); return sName; } ``` Is there any reason for the function return type and the parameter type to both be included? The purpose of the function is to return 1 value. His motivation and use case is that one can do this: ``` std::string sName = ""; SetSomeValue(GetCurrentDataSourceName(sName)); ``` I would think it is better to leave out the parameter like so: ``` const std::string &GetCurrentDataSourceName() { return GetAnotherComponent().GetName(); } ``` But he has me doubting in my coding ability. Edits: The value returned must be const. The code has also been updated to show where the return value comes from. I comes from another component inside the same class;

Original source