why is `std::initializer_list` often passed by value?

It’s passed by value because it’s cheap. std::initializer_list, being a thin wrapper, is most likely implemented as a pair of pointers, so copying is (almost) as cheap as passing by reference. In addition, we’re not actually performing a copy, we’re (usually) performing a move since in most cases the argument is constructed from a temporary anyway. However, this won’t make a difference for performance – moving two pointers is as expensive as copying them.

On the other hand, accessing the elements of a copy may be faster since we avoid one additional dereferencing (that of the reference).

Leave a Comment