【发布时间】:2018-07-11 14:05:01
【问题描述】:
以下两个函数中有什么好的编程习惯:
-
这个:
std::string buildvalue(const std::string &in) { std::string out; out = // Do some calulation bases on input return out; } -
或者这个:
void buildvalue(const std::string &in, std::string &out) { out = // Do some calulation bases on input }
注意 2 函数是调用者可能传递非空字符串。有没有需要注意的地方。
【问题讨论】:
-
1(这必须至少 16 个字符长 :))
-
两者都有一些优点和缺点,值得在特定情况下考虑
-
返回值优化(尤其是复制省略)和移动语义在很大程度上使 1 成为一个非常好的解决方案。
-
用户将非空字符串传递给
out与将第一个解决方案的结果分配给非空字符串的用户没有什么不同。我不明白为什么要格外小心。 -
除非你必须返回多个值,即使那样你也可以不用输出参数,你应该返回函数的输出。