[Cs3] initializer lists and functinos

Mikhail Nesterenko mikhail at cs.kent.edu
Wed Sep 30 14:54:50 EDT 2015


CS3 students,

This is regarding today's discussion. First let us clarify .

* If we want to use the initializer list as an argument to a function or
  return statement. This is perfectly legal and is equivalent to
  invoking an initializer list constructor on the particular object:

  For example, having these two functions:

  void takesVector(vector<int> v){
     for(int i: v) cout << i << ' '; cout << endl;
  }

  vector<int> returnsVector(){
     return {1,2,3,4}; // returns an initialized vector
  }

  The below code works

     takesVector({9, 10, 11, 12}); // initializes parameter
     vector<int> v = returnsVector();


  Since what is being passed as parameter and returned is actually
  a (initializer-list initialized) vector 

* If we want a function to take or return an initializer list, things
  get complicated. First, you need initializer_list header and name:

     #include <initializer_list>
     using std::initializer_list;

  Second, the major issue is the lifetime of the initializer
  list. In the standard, it is a temporary array that exists for as
  long as necessary to initialize the appropriate container. This is
  taken to mean that it does not exist long enough for a return value
  to be used in an expression in the caller function.

  So this code is considered legal and works correctly

     
     void takesIL(initializer_list<int> il){
         vector<int> v = il;
         for(int i: v) cout << i << ' '; cout << endl;
     }

     ...
     takesIL({13, 14, 15, 16});


  while this code is illegal and does not work correctly

    initializer_list<int> returnsIL(){
      return {1,2,3};
    }
 
    ...
    vector<int> u=returnsIL();

Thanks,
-- 
Mikhail


More information about the cs3 mailing list