Ask Your Question
0

Passing Mat object to function

asked 2013-10-12 04:29:11 -0600

eyal gravatar image

updated 2013-10-12 04:47:04 -0600

Moster gravatar image

Hi All,

I have this very simple question that I can get figure it out.

Say I have function

void f(Mat m) { m.at<uchar>(3,3) = 17;}

when I call this function I see that the original Mat object is changed!! as far as I know object passing by value to function in c++ get copied so why when I pass Mat object the original matrix in being changed and not the copied one? Thank u in advance

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
3

answered 2013-10-12 04:43:42 -0600

Moster gravatar image

You are getting a copy of the Mat object, but not a copy of the data. The explanation is simple, just look at the Mat class:

class CV_EXPORTS Mat
{
public:
    // ... a lot of methods ...
    ...

    /*! includes several bit-fields:
         - the magic signature
         - continuity flag
         - depth
         - number of channels
     */
    int flags;
    //! the array dimensionality, >= 2
    int dims;
    //! the number of rows and columns or (-1, -1) when the array has more than 2 dimensions
    int rows, cols;
    //! pointer to the data
    uchar* data;

    //! pointer to the reference counter;
    // when array points to user-allocated data, the pointer is NULL
    int* refcount;

    // other members
    ...
};

You have a uchar pointer to the data. So what happens in your function is that you simply copy the pointer (and of course the rest). The copy of the pointer is still pointing to the original data, so when you modify the Mat, you also modify the input Mat.

edit flag offensive delete link more

Comments

I see. Thank u -:)

eyal gravatar imageeyal ( 2013-10-12 04:56:00 -0600 )edit

Question Tools

Stats

Asked: 2013-10-12 04:29:11 -0600

Seen: 3,209 times

Last updated: Oct 12 '13