c++arraysc++11initializer-listtemp

c++11 is it safe to return an initializer_list value?


I've this simple function:

initializer_list<int> f(){return {1,2,3};}

g++ gives a warning saying:

warning: returning temporary initializer_list does not extend the lifetime of the underlying array [-Winit-list-lifetime]

Is there any risk to return an {1, 2, 3}? Thanks for explanations!


Solution

  • An initializer_list behaves like a reference extending lifetime of a temporary (the temporary being the array).

    Lifetime extension doesn't apply when returning references, so it doesn't apply here too. The compiler is right, the returned list is always dangling.