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 off
; - i don't want rely on rvo;
what best option (and why) avoid return value of f
being copied when
a
may have modified- i know
a
not modified
options:
a) a = f();
b) a&& = f();
c) const a& = f();
d) const a&& = f();
edit:
i say:
- b)
- 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 typea
, move-initializes temporary. not assignment, initialization. move constructor elided popular compiler, provided don't explicitly disallow it, means program ensure storage reserved return value storagea
variable. - c) declares variable
a
const-reference temporary, extending lifetime of temporary. means temporary return value gets storage, , variablea
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
Post a Comment