简体   繁体   English

GCC优化返回值

[英]GCC optimize return value

This question is related to Function returning value vs modifying value passed by reference . 这个问题与函数返回值与引用传递的修改值有关 I want to know if gcc will optimize the following the same way. 我想知道gcc是否会以相同的方式优化以下内容。 Imagine the two functions do the same thing: 想象这两个函数做同样的事情:

Return: 返回:

vector<int> f(...)
{
    vector<int> r;
    ...
    return r;
}

Pass by reference: 通过参考传递:

void f(vector<int> &r, ...)
{
    ...
}

vector<int> r;
f(r, ...)

Pass by reference occurs frequently in (performance critical) GMP functions. 在性能至关重要的GMP功能中,按引用传递经常发生。

Generally compilers are not obligated to do NRVO (Named Return Value Optimization) aka copy elision even if the certain criteria that allow it are met. 通常,即使满足某些条件,编译器也没有义务进行NRVO(命名返回值优化)或复制省略。 Nor a program must be depended on such optimizations as it makes it effectively non portable. 程序也不必依赖于此类优化,因为它实际上使其不可移植。

Now, as far as it concerns the first case, the answer is yes, the compiler is permitted to optimize away the copy of the vector. 现在,就第一种情况而言,答案是肯定的,编译器可以优化去除向量的副本。 In particular this case falls in the following wording of the standard 12.8/p31.1 Copying and moving class objects [class.copy] : 特别是这种情况属于标准12.8 / p31.1复制和移动类对象[class.copy]的以下措辞:

... elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies): ...在以下情况下允许复制/移动操作省略,称为复制删除(可以合并以消除多份副本):

(31.1) — in a return statement in a function with a class return type, when the expression is the name of a nonvolatile automatic object (other than a function parameter or a variable introduced by the exceptiondeclaration of a handler (15.3)) with the same type (ignoring cv-qualification) as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function's return value. (31.1)—在具有类返回类型的函数中的return语句中,当表达式是具有以下内容的非易失性自动对象(函数参数或由处理程序的异常声明(15.3)引入的变量除外)的名称时:与函数返回类型相同(忽略cv限定)的类型,可以通过将自动对象直接构造为函数的返回值来省略复制/移动操作。

Also, from C++11 and beyond std::vector has move facilities and actually the vector is going to be moved. 同样,从C ++ 11开始, std::vector具有移动工具,实际上vector将被移动。

As far as it concerns the second case the answer is no. 至于第二种情况,答案是否定的。 And after all there's no need to, since you pass a reference to the vector. 毕竟没有必要了,因为您传递了对向量的引用。 That is, you pass an alias of the vector (ie the object itself). 也就是说,您传递矢量的别名(即对象本身)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM