RVO与std::move

C++代码样例

std::vector<int64_t> ExtractUniqSkus(const Param& param) {                                                                                                                 
    std::vector<int64_t> ret;

// some basic operations on ret here
ret.push_back(...);
// return std::move(ret); return ret; }

return ret对应汇编

Dump of assembler code for function
   ...
   // 默认构造
   0x00000000032c3ac1 <+43>:  callq  0x31fe232 <std::vector<long, std::allocator<long> >::vector()>
   ...
   0x00000000032c3cf2 <+604>: mov    -0xd8(%rbp),%rax
   0x00000000032c3cf9 <+611>: add    $0xe8,%rsp
   0x00000000032c3d00 <+618>: pop    %rbx
   0x00000000032c3d01 <+619>: pop    %rbp
   0x00000000032c3d02 <+620>: retq  
End of assembler dump.

return std::move(ret)对应汇编

Dump of assembler code for function   ...
   // 默认构造
   0x00000000032c3abe <+40>:  callq  0x31fe232 <std::vector<long, std::allocator<long> >::vector()>
   ...
   // 移动构造
   0x00000000032c3ccb <+565>: callq  0x32cc8c4 <std::vector<long, std::allocator<long> >::vector(std::vector<long, std::allocator<long> >&&)>
   ...
   0x00000000032c3d27 <+657>: mov    -0xf8(%rbp),%rax
   0x00000000032c3d2e <+664>: add    $0x108,%rsp
   0x00000000032c3d35 <+671>: pop    %rbx
   0x00000000032c3d36 <+672>: pop    %rbp
   0x00000000032c3d37 <+673>: retq  
End of assembler dump.

总结

由于有RVO(Return Value Optimization)的存在,如果需要返回对象,就大胆的直接返回对象本身。

通过上面的汇编代码可以看到,直接返回对象,只调用了一次默认构造函数;加上std::move,反倒画蛇添足。

编译器本身的优化,已非常强大。

原文链接: https://www.cnblogs.com/anhongyu/p/12727587.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    RVO与std::move

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/342982

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午1:50
下一篇 2023年3月2日 上午1:51

相关推荐