xmllmx
xmllmx

Reputation: 42245

Why does the C++ standard library always pass std::initializer_list<T> by value rather than by reference?

As a C++ programmer, I have been taught the simple rule of passing parameters:

Passing parameter T by value when sizeof(T) <= sizeof(void*) or for constructing in-place and move in.

However, the C++ standard library seems not comply with the rule. For example, sizeof(std::initializer_list<T>) is greater than sizeof(void*), but std::vector has a constructor:

vector(std::initializer_list<T>, const Allocator&);

Why does the C++ standard library always pass std::initializer_list<T> by value rather than by reference?

Upvotes: 0

Views: 164

Answers (2)

Alex Guteniev
Alex Guteniev

Reputation: 13634

From cppreference on initializer_list:

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

So initializer_list already acts like a reference to a temporary.

The idea behind initializer_list is to move the data from temporaries or copy it from read-only memory directly to the destination container. It is not a container per se.

Upvotes: 2

Jean-Marc Volle
Jean-Marc Volle

Reputation: 3323

Since in the scope of initialization it is known that value will be used (ie copied) as properties of the container (eg vector, map,...) there is no performance gain in passing them by reference.

Upvotes: 2

Related Questions