Why can't g++ (and clang++) avoid string construction here?

Viewed 57

If we write:

std::string foo(const bool b) {
    if (b) {
        return "Hello";
    }
    else {
        return "World";
    }
}

g++ and clang++ will not call a string constructor, but rather manipulate the return string in-place. On the other hand, if we use this style:

std::string bar(const bool b) {
    std::string ret;
    if (b) {
        ret = "Hello";
    }
    else {
        ret = "World";
    }
    return ret;
}

the string class constructor is called, even when compiling with maximum optimization (-O3), and this being a "simple" function. where the next C++ instruction after the assignment is an unconditional return.

(See both examples on GodBolt)

Is this just a missed optimization opportunity in clang++ and g++, or is something compelling them to call the constructor?

This question was inspired by this C++ Weekly episode.

0 Answers
Related