【发布时间】:2014-03-05 08:47:53
【问题描述】:
对于从函数中返回字符串,这两者中哪一个更有效(即我应该使用哪一个):
std::string f(const std::string& s)
{
return s + "some text";
}
或
void f(const std::string& s, std::string &result)
{
result = s + "some text";
}
我知道答案可能取决于特定的编译器。但我想知道现代 C++ 代码中推荐的方法(如果有的话)是什么。
基于下面的“轨道中的轻量竞赛”评论,以下是我在 stackoverflow 上发现的一些相关问题我问了这个问题:
Are the days of passing const std::string & as a parameter over?
Passing std::string by Value or Reference
Pass by value or const reference?
"std::string" or "const std::string&" argument? (the argument is internally copied and modified)
其中没有一个回答我关于从函数返回值与将字符串作为额外参数返回的特定问题。
【问题讨论】:
-
C++11 按值返回,因为如果没有省略则移动
-
returning std::string by value as an argument是什么意思? -
@LightnessRacesinOrbit 是的,这个问题的措辞有点不幸,但这是一个有趣的问题!请阅读我的回答。
-
@Ali 你的观点是正确的,但你至少应该对“过早的优化是万恶之源”表示赞同。
-
@MadScienceDreams 不完全是,请查看我的更新答案!
标签: c++ string performance c++11