Why take a std::initializer_list by rvalue reference vs. by value?

c++, c++11, initializer-list, rvalue-reference

Solution

I'm not sure I have a good reason, but my guess would be that the author of the code may have thought that passing an initializer list by value would make unnecessary copies of the elements in the list. This is, of course, not true - copying an initializer list does not copy the underlying values.

Problem

Most of the C++11 code that takes `std::initializer_list` I've seen takes it by value, but sometimes it is taken by rvalue reference. Is there any good reason to do this? For example, almost every example I've come across does this: ``` class A { public: A(std::initializer_list<int>); }; ``` But I keep seeing this done occasionally: ``` class B { public: B(std::initializer_list<int> &&); }; ``` I understand the use and purpose of rvalue references in general, but why would one of these be preferred over the other in the case of a `std::initializer_list`? The only thing I could think of is that `class A` allows the initializer list to be constructed separately, and `class B` prevents this. ``` std::initializer_list<int> values {1,2,3,4}; A a(values); // valid B b(values); // error ``` But I can't think of a good reason why preventing that would be a desirable thing to accomplish. So, why would one take a `std::initializer_list` by rvalue reference instead of by value?

Original source