假设编译时禁用复制省略,为了消除不必要的复制(模拟复制省略),以下操作是否有效?
Container getContainer() {
Container c;
return c;
}
int main() {
Container&& contianer = getContainer();
}
我没有足够的资格来讨论 NRVO 标准的细微差别,但我们可以尝试与下面的代码片段类似地进行测试(使用 GCC 13.2 和 C++11 模式加上
-fno-elide-constructors
选项。live):
#include <vector>
#include <cstdio>
std::vector<int> create( const int in )
{
std::vector<int> foo ( 5, in );
return foo;
}
int main( int argc, char* argv[] )
{
std::vector<int>&& result { create( argc ) }; // remove `&&` and it will result
// in slightly more assembly code
for ( auto&& val : result )
std::printf( "%d\n", val );
}
似乎将
&&
添加到 result
类型中就不再需要一些额外的 mov
和 movdqa
指令。话虽如此,您可能需要衡量性能差异。在某些情况下,生成的机器代码可能会产生误导。
Clang 17.0.1 另一方面,为两种情况生成相同的代码(有或没有
&&
)。