NRVO for C ++ std :: string

米哈尔·P。

我试图找到一些有关std :: string命名返回值优化(NVRO)的信息。我什至不确定这是否适用,但我想知道从可读性和性能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;
}

如注释中所示:

  1. nvro会在“第一手”中进行吗?

  2. 是否有更好的(清洁/性能)解决方案?

我的意图是创建一个辅助函数,该函数将根据给定的参数连接正确的字符串

泰德·林格莫
  1. 在C ++ 11和14中,在这种情况下允许复制省略从C ++ 17开始,必须对返回值进行优化(并且不再将其视为copy elision)。

  2. 通过查看三个候选函数@ godbolt并不能看出来,但是我并没有做太多的汇编。但是,这看起来可能会更干净一些:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章