'const Eigen::SparseMatrix can be modified by using non-const iterator and valueRef()

It seems to me that a const Eigen::SparseMatrix can still be modified by using a non-const SparseMatrix::InnerIterator and valueRef() function. Here is the code snippet

const Eigen::SparseMatrix<double> sp = Eigen::Matrix2d::Identity().sparseView();
for (int i = 0; i < 2; ++i) {
  for (Eigen::SparseMatrix<double>::InnerIterator it(sp, i); it; ++it) {
    // Modify the value with valueRef();
    it.valueRef() = 3;
  }
}
// This prints 3 * I.
std::cout << sp << "\n";

Is this a flaw in Eigen's design? How can I make Eigen::SparseMatrix immutable?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source