c++ - 对函数的输出字符串参数使用交换与赋值
问题描述
如果我们有一个函数应该基于某种计算将字符串值填充到它的 out 参数中,那么我们应该更喜欢使用哪一个,为什么?
void function(string& x)
{
// In actual code, this value is calculated based on certain conditions
string temp = "Stack Overflow";
x.swap(temp);
}
VS
void function(string& x)
{
// In actual code, this value is calculated based on certain conditions
string temp = "Stack Overflow";
x = temp;
}
解决方案
如果您不打算在交换/分配之后再使用x
' 的原始内容function
,则不需要交换。
赋值将擦除 的当前内容x
,但如果没问题,则(复制)赋值
x = temp;
很好。
如果你也不需要temp
在temp
后面的 in 中使用之前的内容function
,那么你可以移动 assign 代替:
x = std::move(temp);
(需要#include<utility>
)
移动可能比复制或交换更快,但细节取决于std::string
实现。我预计移动分配和交换之间的性能不会有任何显着差异,但是复制分配可能会对最初的字符串进行分配和完整复制,temp
因此在性能方面可能是最糟糕的选择。
如评论中所述,您可能根本不需要输出参数。这很少有原因。通常可以将函数的输出作为返回值提供:
std::string function()
{
// In actual code, this value is calculated based on certain conditions
string temp = "Stack Overflow";
return temp;
}
//...
std::string result = function();
这总是会比输出参数表现得更好,因为它总是会移动temp
到result
甚至可能使用所谓的返回值优化完全优化移动操作,这对于输出参数是不可能的,并且因为(如果函数未内联)它也不需要通过函数参数中的引用进行额外的间接寻址。
即使您有多个返回值,您仍然可以返回一个std::pair
或std::tuple
其中一个并在调用方站点上解压它们。
推荐阅读
- c# - 组合不显示选择项目并显示为项目列表
- evernote - 印象笔记速率限制
- javascript - 在 Web 浏览器控制台中自省 ECMAScript 6 模块成员
- python - Pygame:如何将分离轴定理(SAT)应用于旋转正方形?
- jquery - 设置动态表中下拉菜单的值
- angular - 尽管在 url 中捕获了正确的值,但 Angular 9 组件不会更改页面
- python - Anaconda env 说没有安装 python
- android - 使用 Tablayout 和 ViewPager2 样式特定选项卡
- asp.net-core - Swagger UI - 未知类型:整数问题
- python - Python 3.7 变量链式方法调用