Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In almost every post I see on SO, involving a std::initializer_list, people tend to pass a std::initializer_list by value. According to this article:

http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

one should pass by value, if one wants to make a copy of the passed object. But copying a std::initializer_list is not a good idea, as

Copying a std::initializer_list does not copy the underlying objects. The underlying array is not guaranteed to exist after the lifetime of the original initializer list object has ended.

So why is an instance of it often passed by value and not by, say const&, which guaranteed does not make a needless copy?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...