我尝试查找有关 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;
}
如评论:
nvro 会在“第一”中执行吗?
有没有更好(更清洁/性能)的方法来解决这个问题?
我的目的是创建一个辅助函数,它将根据给定的参数连接正确的字符串