Search code examples
eigentensortensor-indexing

Why the first index of a multidimensional matrix of Eigen::Tensor able to loop through all the members of the tensor?


Why the first index of a multidimensional matrix of Eigen::Tensor able to loop through all the members of the tensor successfully?

I am new to Eigen::Tensor library and still testing it to adopt it for my code.

#include <Eigen/CXX11/Tensor>

using namespace Eigen;

int main()
{
    Tensor<double, 3> t3d (2, 3, 4);
    t3d.setValues(
        {{{0, 6, 12, 18}, {2, 8, 14, 20}, {4, 10, 16, 22}},
         {{1, 7, 13, 19}, {3, 9, 15, 21}, {5, 11, 17, 23}}});
    for (int i = 0; i < t3d.size(); ++i)
    {
        cout << t3d(i, 0, 0) << '\t';
    }
}

It should give an error of some type (core dumped, etc.) or access unassigned portions of the memory to give random values. Surprisingly, this correctly outputs all the members of the tensor:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23


Solution

  • As of today, the behavior of accessing out-of-range elements of an Eigen::Tensor is not documented. But you can actually have it generate assertions when compiling with -DEIGEN_INTERNAL_DEBUGGING (however, this can make execution significantly slower).

    Godbolt-Demo: https://godbolt.org/z/RrnjXS