C++NRVO guarantees? Or better prefer non-const ref param or shared_ptr?

 ̄綄美尐妖づ 提交于 2019-12-06 07:08:22
Bart Vandewoestyne

In Section 12.8/31, the C++11 standard writes

"When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects."

That means your compiler might never use RVO (although most compilers do support it).

Given the above, Scott Meyers' advice from 'Effective Modern C++' (Item 25) is

"Never apply std::move or std::forward to local objects if they would otherwise be eligible for the return value optimization."

The rationale is as follows:

  • If you do apply std::move, then the move constructor (which is more expensive than RVO) will be used, even if RVO was a possibility. So you possibly lose some performance there.
  • If you don't apply std::move, you leave room for RVO should your compiler support it. If your compiler doesn't support RVO, you'll use the move constructor anyway. So you possibly gain some performance there.

Clang will have -Wpessimizing-move and -Wredundant-move warnings for this. See this link.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!