I tried to use constants when returning a value from a function/method, but I don't see any benefits of using it because we can't modify the returned value from inside a function. Or even from outside.
class Foo {
std::string m_val;
public:
void set(const std::string v) {
m_val = v;
}
const std::string get() const {
return m_val;
}
};
int main() {
Foo f;
f.set("Hello world!");
/* (1) Wrong
f.get() = "Thanks";
*/
/* (2) You can change the "retVal" value except if you used const with "retVal".
std::string retVal = f.get();
retVal = "Thank you";
*/
return 0;
}
Maybe returning a const value is not useless, as I think, but I still didn't find anything that changes my mind, so I asked my question here to clarify that.
std::string s = f.get(); s = "a";.const. What you should be is to return aconst&instead.constto prevent silly mistakes of the caller but that was long before there was move semanticsm_val, it might as well be public. Your attempt to modify the member throughget()should always be called out during code review as well becuase either the function is poorly named or you're doing it wrong.