Q:

Passing cv::Mat by reference or return it?

I was wondering which version of this function is more efficient:
void myimread (cv::Mat &mat, const std::string &imgname){
  mat = imread(imgname);
}

or
cv::Mat myimread (const std::string &imgname){
  return imread(imgname);
}

From my knowledge, cv::Mat is kinda of a smart pointer and combined with the move semantic that cv::Mat should implement (again, if I'm not wrong) the second version should be not more expensive than the first one.

A:

If copy elision gets applied, the 2nd case would be more efficient.
For the 1st case, the usage would be:
cv::Mat mat;            // default constructed
myimread(mat, imgname); // copy assigned by imread(imgname) inside myimread

For the 2nd case:
cv::Mat mat = myimread(imgname); // mat is constructed by imread(imgname) directly; copy/move operation is omitted

From C++17 when the operand of a return statement is a prvalue and the return type of the function is the same as the type of that prvalue, copy elision is guaranteed.

