为什么 C++ 标准库总是按值而不是按引用传递 std::initializer_list<T>?
Why does the C++ standard library always pass std::initializer_list<T> by value rather than by reference?
作为一名C++程序员,我学到了传递参数的简单规则:
Passing parameter T
by value when sizeof(T) <= sizeof(void*)
or for constructing in-place and move in.
但是,C++标准库似乎不符合这个规则。对于example,sizeof(std::initializer_list<T>)
大于sizeof(void*)
,但是std::vector
有一个构造函数:
vector(std::initializer_list<T>, const Allocator&);
为什么C++标准库总是通过std::initializer_list<T>
按值而不是按引用?
由于在初始化范围内已知值将用作(即复制)作为容器的属性(例如向量、映射等),因此通过引用传递它们不会提高性能。
来自 initializer_list 上的 cppreference:
The lifetime of the underlying array is the same as any other temporary object, except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary (with the same exceptions, such as for initializing a non-static class member).
所以 initializer_list
已经充当了对临时文件的引用。
initializer_list
背后的想法是将数据从临时文件中移动或将其从只读内存直接复制到目标容器中。它本身不是容器。
作为一名C++程序员,我学到了传递参数的简单规则:
Passing parameter
T
by value whensizeof(T) <= sizeof(void*)
or for constructing in-place and move in.
但是,C++标准库似乎不符合这个规则。对于example,sizeof(std::initializer_list<T>)
大于sizeof(void*)
,但是std::vector
有一个构造函数:
vector(std::initializer_list<T>, const Allocator&);
为什么C++标准库总是通过std::initializer_list<T>
按值而不是按引用?
由于在初始化范围内已知值将用作(即复制)作为容器的属性(例如向量、映射等),因此通过引用传递它们不会提高性能。
来自 initializer_list 上的 cppreference:
The lifetime of the underlying array is the same as any other temporary object, except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary (with the same exceptions, such as for initializing a non-static class member).
所以 initializer_list
已经充当了对临时文件的引用。
initializer_list
背后的想法是将数据从临时文件中移动或将其从只读内存直接复制到目标容器中。它本身不是容器。