【发布时间】:2019-06-03 11:15:34
【问题描述】:
我尝试查找有关 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;
}
在 cmets 中:
nvro 会在“frist”中执行吗?
有没有更好(更清洁/性能)的方法来解决这个问题?
我的目的是创建一个辅助函数,它将根据给定的参数连接正确的字符串
【问题讨论】:
-
1.编译器可以在那个地方使用 RVO。
-
@MichalP 此问题仍列为未回答。没有任何建议的答案可以解决问题吗?