C++ return a std::string &

  • A+
std::string &func(int vlu) {     std::string str;     str = std::to_string(vlu) + "something";      return str; } 

the function above is unsafe clearly.
Following is another version.

std::string &func(int vlu) {     return std::to_string(vlu) + "something"; }   

I have some questions:
the compiler(gcc), in the second version, doesn't give me any warning. Is it safe? I just think that compiler(or something?) will create a temporary variable to hold the return of expression std::to_string(vlu) + "something". So the second version is unsafe too. and I right?


No, neither program is safe. In both cases the returned reference is dangling and the behaviour of using the reference will be undefined.

The second program is also ill-formed, because it attempts to bind an lvalue reference (that is returned) to an rvalue (the temporary). The second program might be considered "less unsafe", since a compiler might choose to not compile it.

To fix the function: Don't attempt to return a reference, when the purpose is to return a new object. Return a value instead.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: