为什么`std :: initializer_list`经常通过值传递? [英] why is `std::initializer_list` often passed by value?
问题描述
在我在SO上看到的几乎每个帖子中,涉及到一个 std :: initializer_list
,人们倾向于传递 std :: initializer_list
按值。根据本文:
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/
pass by value,如果想要创建传递对象的副本。但是复制 std :: initializer_list
不是一个好主意,因为
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
a
std :: initializer_list
不复制基础对象。
在
的生命周期结束后,底层数组不能保证存在。
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.
所以为什么它的一个实例经常通过值而不是通过 const&
,这保证不会造成不必要的副本?
So why is an instance of it often passed by value and not by, say const&
, which guaranteed does not make a needless copy?
推荐答案
它是通过价值,因为它很便宜。 std :: initializer_list
作为一个thin wrapper,最有可能被实现为一对指针,因此复制与通过引用传递一样便宜。此外,我们实际上并不执行副本,我们(通常)执行移动,因为在大多数情况下,参数是从临时建立的。但是,这不会对性能产生影响 - 移动两个指针和复制它们一样昂贵。
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).
这篇关于为什么`std :: initializer_list`经常通过值传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!