c++11 - Which type to declare to avoid copy and make sure returned value is moved -


suppose that

  • i have function a f();
  • i want initialize local variable a return value of f;
  • i don't want rely on rvo;

what best option (and why) avoid return value of f being copied when

  1. a may have modified
  2. i know a not modified

options:

a) a = f(); b) a&& = f(); c) const a& = f(); d) const a&& = f();


edit:

i say:

  1. b)
  2. c)

because both use references , avoid copy (which avoided rvo well, not guaranteed). how come see option a) suggested of time?

i guess heart of question is: a) has same effect c), why not use c) instead of a), make things explicit , independent on compiler?

so how come see option a) suggested of time?

because 4 options return value exact same way. thing changes way bind variable returned temporary.

  • a) declares variable a of type a , move-initializes temporary. not assignment, initialization. move constructor elided popular compiler, provided don't explicitly disallow it, means program ensure storage reserved return value storage a variable.
  • c) declares variable a const-reference temporary, extending lifetime of temporary. means temporary return value gets storage, , variable a refer it. compiler, knowing statically reference points returned value, generate same code a).
  • b) , d), not sure they're for. (and if works) not take rvalue reference @ point. if need one, explicitly std::move variable later.

now :

a may have modified

if a may modified, use :

auto = f(); 

i know not modified

if know a not modified, use :

const auto = f(); 

the use of auto prevent type mismatch. (and such, implicit conversion a if f happens not return type a after all. oh, maintainers...)


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -