c++ - why is `std::initializer_list` often passed by value? -
in every post see on so, involving std::initializer_list
, people tend pass std::initializer_list
value. according article:
http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/
one should pass value, if 1 wants make copy of passed object. copying std::initializer_list
not idea, as
copying
std::initializer_list
not copy underlying objects. underlying array not guaranteed exist after lifetime of original initializer list object has ended.
so why instance of passed value , not by, const&
, guaranteed not make needless copy?
it’s passed value because it’s cheap. std::initializer_list
, being thin wrapper, implemented pair of pointers, copying (almost) cheap passing reference. in addition, we’re not performing copy, we’re (usually) performing move since in cases argument constructed temporary anyway. however, won’t make difference performance – moving 2 pointers expensive copying them.
on other hand, accessing elements of copy may faster since avoid 1 additional dereferencing (that of reference).
Comments
Post a Comment