How does the range-based for work for plain arrays?

后端 未结 6 1114
暗喜
暗喜 2020-11-27 11:19

In C++11 you can use a range-based for, which acts as the foreach of other languages. It works even with plain C arrays:

int number         


        
6条回答
  •  孤独总比滥情好
    2020-11-27 11:50

    Some sample code to demonstrate the difference between arrays on Stack vs arrays on Heap

    
    /**
     * Question: Can we use range based for built-in arrays
     * Answer: Maybe
     * 1) Yes, when array is on the Stack
     * 2) No, when array is the Heap
     * 3) Yes, When the array is on the Stack,
     *    but the array elements are on the HEAP
     */
    void testStackHeapArrays() {
      int Size = 5;
      Square StackSquares[Size];  // 5 Square's on Stack
      int StackInts[Size];        // 5 int's on Stack
      // auto is Square, passed as constant reference
      for (const auto &Sq : StackSquares)
        cout << "StackSquare has length " << Sq.getLength() << endl;
      // auto is int, passed as constant reference
      // the int values are whatever is in memory!!!
      for (const auto &I : StackInts)
        cout << "StackInts value is " << I << endl;
    
      // Better version would be: auto HeapSquares = new Square[Size];
      Square *HeapSquares = new Square[Size];   // 5 Square's on Heap
      int *HeapInts = new int[Size];            // 5 int's on Heap
    
      // does not compile,
      // *HeapSquares is a pointer to the start of a memory location,
      // compiler cannot know how many Square's it has
      // for (auto &Sq : HeapSquares)
      //    cout << "HeapSquare has length " << Sq.getLength() << endl;
    
      // does not compile, same reason as above
      // for (const auto &I : HeapInts)
      //  cout << "HeapInts value is " << I << endl;
    
      // Create 3 Square objects on the Heap
      // Create an array of size-3 on the Stack with Square pointers
      // size of array is known to compiler
      Square *HeapSquares2[]{new Square(23), new Square(57), new Square(99)};
      // auto is Square*, passed as constant reference
      for (const auto &Sq : HeapSquares2)
        cout << "HeapSquare2 has length " << Sq->getLength() << endl;
    
      // Create 3 int objects on the Heap
      // Create an array of size-3 on the Stack with int pointers
      // size of array is known to compiler
      int *HeapInts2[]{new int(23), new int(57), new int(99)};
      // auto is int*, passed as constant reference
      for (const auto &I : HeapInts2)
        cout << "HeapInts2 has value " << *I << endl;
    
      delete[] HeapSquares;
      delete[] HeapInts;
      for (const auto &Sq : HeapSquares2) delete Sq;
      for (const auto &I : HeapInts2) delete I;
      // cannot delete HeapSquares2 or HeapInts2 since those arrays are on Stack
    }
    

提交回复
热议问题