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; }
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.
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