首页 > 解决方案 > 对函数的输出字符串参数使用交换与赋值

问题描述

如果我们有一个函数应该基于某种计算将字符串值填充到它的 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;
}

标签: c++c++11

解决方案


如果您不打算在交换/分配之后再使用x' 的原始内容function,则不需要交换。

赋值将擦除 的当前内容x,但如果没问题,则(复制)赋值

x = temp;

很好。

如果你也不需要temptemp后面的 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();

这总是会比输出参数表现得更好,因为它总是会移动tempresult甚至可能使用所谓的返回值优化完全优化移动操作,这对于输出参数是不可能的,并且因为(如果函数未内联)它也不需要通过函数参数中的引用进行额外的间接寻址。

即使您有多个返回值,您仍然可以返回一个std::pairstd::tuple其中一个并在调用方站点上解压它们。


推荐阅读