Which type to declare to avoid copy and make sure returned value is moved

被刻印的时光 ゝ 提交于 2019-12-03 23:07:02

So how come I see option a) suggested most of the time?

Because all 4 options return the value the exact same way. The only thing that changes is the way you bind a variable to the returned temporary.

  • a) Declares a variable a of type A and move-initializes it from the temporary. This is not an assignment, this is initialization. The move constructor will be elided by any popular compiler, provided that you don't explicitly disallow it, which means that the program will just ensure that the storage reserved for the return value is the storage for the a variable.
  • c) Declares a variable a which is a const-reference to the temporary, extending the lifetime of the temporary. Which means that the temporary return value gets storage, and the variable a will refer to it. The compiler, knowing statically that the reference points to the returned value, will effectively generate the same code as a).
  • b) and d), I am not really sure what they're good for. (and even if that works) I would not take an rvalue reference at this point. If I need one, I would explicitly std::move the variable later.

Now :

a may have to be modified

If a may be modified, use :

auto a = f();

I know that a will not be modified

If you know that a will not be modified, use :

const auto a = f();

The use of auto will prevent any type mismatch. (and as such, any implicit conversion to A if f happens not to return type A after all. Oh, those maintainers...)

If class A have move-constructor then just use A a = f(); If you know nothing about class A you can rely only on RVO or NRVO optimization.

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