Wednesday, July 6, 2022

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

Issue

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?


Solution

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.



Answered By - Alex Guteniev
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.