Std :: initializer_list and reference types

Can std::initializer_list contain reference types (both rvalue and lvalue)? Or do you need to use pointers or a reference wrapper (e.g. std::ref )?

EDIT:

More clarification may be required:

I have a member variable, ::std::vector<std::function<void()> > , into which I would like to forward the lambda object. This is usually done using emplace_back , but I wanted to do this in the constructor initialization list. Alas, as I read, this would make shipping impossible.

+7
c ++ c ++ 11 initializer-list
source share
2 answers

Can std::initializer_list contain reference types (both rvalue and lvalue)?

std::initializer_list<T> does not contain references to its elements. It uses copy-semantics, holding its values โ€‹โ€‹as const objects:

18.9 Initializer List [support.initlist]

An object of type initializer_list<E> provides access to an array of objects of type const E

An initializer_list links will result in a compilation error because inertial pointers are used for iterators:

 #include <initializer_list> int main() { int x; std::initializer_list<int&> l = {x}; // In instantiation of 'class std::initializer_list<int&>': // error: forming pointer to reference type 'int&' // typedef const _E* iterator; } 

An initializer_list also does not support move-semantics, since const objects cannot be moved. Saving objects to std::reference_wrapper<T> is the most viable solution if you want to save reference semantics.

+5
source share

From http://www.cplusplus.com/reference/initializer_list/initializer_list/

Initializer_list objects are created automatically as if an array of elements of type T were selected

therefore, they cannot be used with something like std::initializer_list<int&> . The reason is the same for which the following gives a compiler error

 int& arr[20]; 

error: declaration of 'arr as an array of links

and this is dictated by the C ++ standard: stack overflow

+4
source share

All Articles