Write to a CV::Mat from a higher scope within a function I've written this function to read matrices from the ROS parameter server.

void read_matrix_from_param(ros::NodeHandle nodehandle, std::string param, cv::Mat &amp;cv_matrix) {
      // 1D vector for temporarily holding matrix elements
      std::vector&lt;double&gt; _data;

      // matrix dimensions
      int _rows, _cols;

      // read from param server
      nodehandle.getParam(param + std::string("/data"), _data);
      nodehandle.getParam(param + std::string("/rows"), _rows);
      nodehandle.getParam(param + std::string("/cols"), _cols);

      // create cv::Mat and copy into cv_matrix
      cv::Mat(_rows, _cols, CV_64F, _data.data()).copyTo(cv_matrix);
  }


called like this:

cv::Mat test_matrix1, test_matrix2;
read_matrix_from_param(private_nh, std::string("camera_matrix"), test_matrix1);
read_matrix_from_param(private_nh, std::string("distortion_coefficients"), test_matrix2);


This works as expected but my editor gives me a style-guide warning for the function signature.

runtime/references: Is this a non-const reference? If so, make const or use a pointer: cv::Mat &amp;cv_matrix


So how should this be done? I have tried to do as the style-guide suggests but been unable to get working code again.
Assuming the matrix is always empty when passed into the function, the more normal way to write this would be to avoid any side effects and make cv_matrix the return type. i.e

cv::Mat read_matrix_from_param(ros::NodeHandle nodehandle, const std::string&amp; param)
{
    cv::Mat cv_matrix

    ...
    return cv_matrix;
}


As a side point you should pass in param and possibly nodehandle, as const &amp; to avoid unnecessary copies.

If this is not the case and you may pass in non-empty matrices ( I think that wouldn't make sense here ), then I would say using a non-const ref is fine. Alternative you could use a pointer i.e.

void read_matrix_from_param(ros::NodeHandle nodehandle, std::string param, cv::Mat *cv_matrix)
{
    ...

    cv::Mat(_rows, _cols, CV_64F, _data.data()).copyTo(*cv_matrix);
}


called as

read_matrix_from_param(private_nh, std::string("camera_matrix"), &amp;test_matrix1);

Personally I wouldn't use a pointer and Core C++ Guidelines recommends a reference, but looks like it is the style recommended by google see https://softwareengineering.stackexchange.com/questions/299021/non-optional-pointers-vs-non-const-references-in-c . If you are using clang-tidy google style guidelines are an option in that I believe so that may be where this warning is coming from.