c++c++14nrvo

NRVO for C++ std::string


I tried finding some info about std::string Named Return Value Optimization (NVRO). I'm not even sure if this is applicable but I'm wondering which would be better from both readability and performance POV.

std::string first(const bool condition)
{
    std::string info = "This";
    info += condition 
        ? " is" 
        : " irrelevant";  //.append()

    info += " info.";

    return info; // nrvo here?
}

std::string second(const bool condition)
{
    const auto firstPart = "First part";
    const auto anotherPart = condition 
        ? " second part" 
        : " irrelevant ";  //.append()

    return std::string{}.append(firstPart).append(anotherPart);
}

std::string third(const bool condition)
{
    //would avoid due to poor readability if strings are long
    return std::string{}
        .append("First part")
        .append(condition ? " second" : "irrelevant");
}

int main()
{
    // printf("Hello World");
    const auto irrelevant {true};

    std::cout<<first(irrelevant)<<std::endl;
    std::cout<<second(irrelevant)<<std::endl;
    std::cout<<third(irrelevant)<<std::endl;

    return 0;
}

As in comments:

  1. Will the nvro be performed in "frist"?

  2. Is there a better (cleaner/performance) way of solving this problem?

My intention is to create a helper function that will concatenate correct string based on given param


Solution

    1. In C++11 and 14, copy elision is permitted in that case. From C++17, return value optimization is mandatory (and no longer considered as copy elision).

    2. Not that I can see by looking at the three candidate functions @ godbolt but I don't do much assembler. This may look a little cleaner though:

        std::string fourth(const bool condition) {
            return std::string{"First part "} += (condition ? "second" : "irrelevant");
        }