I have written a matrix class Matrix<T> for which I have implemented a wrapper function for cblas_dgemm. cblas_dgemm requires to pass my input matrices as double*. However, I want my wrapper to work with const Matrices as well (for which I can only provide a const double*). Within my call to cblas_dgemm I cast the const away with const_cast<double*>. My question is: Can I rely that cblas_dgemm actually only reads my input matrices, so that the const_cast is safe? I know, of course, that eventually the input matrices are the same after the call to dgemm, but maybe BLAS does some temporary changes to my matrix?

Matrix<double> wrapper_to_cblas(const Matrix<double>&a, const Matrix<double>& b) {
cblas_dgemm(/*here I cast const double* to double* */)

Edit: The BLAS implementation I am using actually allows for the use of const double*, so it really seems to be implementation-dependent.

  • $\begingroup$ netlib.org/lapack/explore-html/dc/d18/… $\endgroup$ Aug 1, 2022 at 18:10
  • $\begingroup$ @Aruralreader There are many BLAS implementations around; just showing that one of them does not mutate inputs does not guarantee that all do. Ideally it should be mentioned in the interface / docs. I can only see it "defined via omission" though; usually it is mentioned when arguments are mutated. $\endgroup$ Aug 1, 2022 at 19:49
  • $\begingroup$ The hint really was for the OP to look at the code being used. $\endgroup$ Aug 1, 2022 at 22:02
  • $\begingroup$ @Aruralreader It's not that easy to look at the code being used, though. That's the Blas reference implementation, but in practice if you want good performance you'll be using the more complex ATLAS, or MKL which is closed-source. $\endgroup$ Aug 2, 2022 at 7:38
  • 2
    $\begingroup$ I checked the BLAS implementation I am using (OpenBLAS) and it actually works fine together with const double* so false alarm I guess :) $\endgroup$
    – Urwald
    Aug 2, 2022 at 8:54


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.