9
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?

14
  • 1
    clang and gcc(8.2) do emit warnings: prog.cc:5:12: error: non-const lvalue reference to type 'basic_string<...>' cannot bind to a temporary of type 'basic_string<...>' return std::to_string(vlu) + "something"; ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1 error generated. Commented Oct 29, 2018 at 10:54
  • 4
    Yes, the second version is unsafe also. A compiler is not obligated to warn you about undefined behavior. If you get a warning, consider it to be no more than an unexpected surprise that your compiler detected your own bug for you. Commented Oct 29, 2018 at 10:54
  • The 2nd version is definitely unsafe. I think it should be a gcc bug for not emitting warning, or maybe, it involves RVO and thus affecting the analysis Commented Oct 29, 2018 at 10:55
  • 2
    Possible duplicate of C++ Returning reference to local variable Commented Oct 29, 2018 at 10:56
  • its not just "unsafe". unsafe sounds as if there is a chance that it could to something wrong, but in fact there is no chance that the function could do something right... Commented Oct 29, 2018 at 11:00

1 Answer 1

13

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 an object instead.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.