C++ auto& vs auto -
when creating local variables, correct use (const) auto&
or auto
?
e.g.:
someclass object; const auto result = object.somemethod();
or const auto& result = object.somemethod();
where somemethod() returns non-primitive value - maybe user-defined type. understanding const auto& result
correct since result returned somemethod() call copy constructor returned type. please correct me if wrong.
what primitive types? assume const auto sum = 1 + 2;
correct.
does apply range based loops?
for(const auto& object : objects)
auto
, auto &&
cover of cases:
use
auto
when need local copy. never produce reference. copy (or move) constructor must exist, might not called, due copy elision optimization.use
auto &&
when don't care if object local or not. technically, produce reference, if initializer temporary (e.g., function returns value), behave own local object.also,
auto &&
doesn't guarantee object modifiable, either. givenconst
object or reference, deduceconst
. however, modifiability assumed, given specific context.
auto &
, auto const &
little more specific:
auto &
guarantees sharing variable else. reference , never temporary.auto const &
auto &&
, provides read-only access.
what primitive/non-primitive types?
there no difference.
does apply range based loops?
yes. applying above principles,
- use
auto &&
ability modify , discard values of sequence within loop. (that is, unless container provides read-only view, suchstd::initializer_list
, in caseauto const &
.) - use
auto &
modify values of sequence in meaningful way. - use
auto const &
read-only access. - use
auto
work (modifiable) copies.
you mention auto const
no reference. works, it's not commonly used because there seldom advantage read-only access own.
Comments
Post a Comment