dimanche 29 novembre 2015

How can a C++11 array not store its size?

From cplusplus.com :

Internally, an array does not keep any data other than the elements it contains (not even its size, which is a template parameter, fixed on compile time).

I understand that this means that using array is similar to using int[] and sizeof in the same scope. But is this code valid or is relying on undefined behavior?

class A {
    array<int, 10> arr;
    void setArr() {
        for (int& i : arr)
            i = 42;
    }
    void printArr() {
        for (int i : arr)
            cout << i << endl;
    }
};

How does the compiler know when to stop the foreach without storing the array size on the heap or stack? I ran it, the code works.

Aucun commentaire:

Enregistrer un commentaire