0

Why it safe to use Armadillo when an apparent UB is widely present inside it?

Armadillo often uses rw(...) function (which is basically a const_cast) to modify a const member of a class.

So here is the rw:

template<typename T1> constexpr static T1& rw (const T1& x) { return const_cast<T1& >(x); }

and here as the Mat class:

class Mat : public Base< eT, Mat<eT> >
  {
  public:
  
  typedef eT                                elem_type;  //!< the type of elements stored in the matrix
  typedef typename get_pod_type<eT>::result  pod_type;  //!< if eT is std::complex<T>, pod_type is T; otherwise pod_type is eT
  
  const uword  n_rows;    //!< number of rows               (read-only)
  const uword  n_cols;    //!< number of columns            (read-only)
  const uword  n_elem;    //!< number of elements           (read-only)
  const uword  n_alloc;   //!< number of allocated elements (read-only); NOTE: n_alloc can be 0, even if n_elem > 0
  const uhword vec_state; //!< 0: matrix layout; 1: column vector layout; 2: row vector layout
  const uhword mem_state;
...

and inside Mat::init_warm (which is used for example in the = operator) we have:

 access::rw(n_rows)    = in_n_rows;
 access::rw(n_cols)    = in_n_cols;
 access::rw(n_elem)    = new_n_elem;
 access::rw(mem_state) = 0;

Isn't it just a pure example of UB? Or if not, why is it safe? It's been bothering me for some time.

0 Answers0