Search code examples
c++variable-assignment

What's the difference between using an Assignment Constructor vs. normal assignment here?


I've spent some time trying to understand some C++ code, and I have background in C and Java. The code in question used what looked to be shorthand of some kind that I didn't recognize or understand for some time. I know now that they were using assignment constructors to assign variables, something that doesn't exist in either.

Here is the example:

cv::Mat rgb(raw_h1 + raw_h2, raw_w1, CV_8UC3);

is roughly equivalent I found to:

cv::Mat rgb = cv::Mat(raw_h1 + raw_h2, raw_w1, CV_8UC3);

At first I didn't know what I was looking at, though through debugging I knew what the effects were.

Later on, we have similarly a new piece of code:

cv::Mat dst_roi = rgb(cv::Rect(0, 0, raw_w1, raw_h1));

which seems to be a shorthand to call cv::Mat constructor:

Mat(const Mat& m, const Rect& roi);

Which would make sense that a roughly equivalent statement would be:

cv::Mat dst_roi = cv::Mat(rgb, cv::Rect(0, 0, raw_w1, raw_h1));

In fact, replacing the former code with the latter introduces no compiler error, so I likely am onto something here.

What is this second shorthand called where you can call a constructor on an already declared object to use the object as a parameter in the constructor of the object class?

Why would you use this form of assignment constructor over the other method of assignment as I have displayed? Does it involve speed? Conciseness? Or something that I don't know myself?

If I'm incorrect on any of my assumptions, please do not be afraid to point that out, but at least on the first one, I've been able to test and verify that I am correct.


Solution

  • The conversion you have is not correct.

    cv::Mat rgb(raw_h1 + raw_h2, raw_w1, CV_8UC3); // (1)
    cv::Mat dst_roi = rgb(cv::Rect(0, 0, raw_w1, raw_h1)); // (2)
    

    (2) actually calls cv::Mat::operator()(const Rect &) which returns a new cv::Mat.

    Then you copy initialize it into dst_roi (calls the copy constructor, or with C++17 guaranteed copy elision, no copy at all).