Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

you have to be extremely careful, when constructing a Mat like this.

what you've got there, is called a borrowed pointer, the memory does not get copied (only the pointer), thus, when the original pointer goes out of scope (e.g. when you leave that function), it is invalid.

there are a couple of solutions:

  1. clone it (make a deep copy):

    return cv::Mat(2, 2, CV_64FC1, matrix).clone();

  2. use Matx class:

    Matx22d m(1,0,1,0); return m;

  3. use Mat_<double> and the << operator:

    Mat_<double> m(2,2); m << 1,0,1,0; return m;

you have to be extremely careful, when constructing a Mat like this.

what you've got there, is called a borrowed pointer, the memory does not get copied (only the pointer), thus, when the original pointer goes out of scope (e.g. when you leave that function), it is invalid.invalid !

there are a couple of solutions:

  1. clone it (make a deep copy):

    return cv::Mat(2, 2, CV_64FC1, matrix).clone();

  2. use Matx class:

    Matx22d m(1,0,1,0); return m;

  3. use Mat_<double> and the << operator:

    Mat_<double> m(2,2); m << 1,0,1,0; return m;

you have to be extremely careful, when constructing a Mat like this.

what you've got there, is called a borrowed pointer, the memory does not get copied (only the pointer), thus, when the original pointer goes out of scope (e.g. when you leave that function), it is invalid !

there are a couple of solutions:

  1. clone it (make a deep copy):

    return cv::Mat(2, 2, CV_64FC1, matrix).clone();

  2. use Matx class:

    Matx22d m(1,0,1,0); return m;

  3. use Mat_<double> and the << operator:

    Mat_<double> m(2,2); m << 1,0,1,0; return m;

  4. don't make it a (seperate) function. as long as your initialization and usage stays in the same scope, you're safe.

you have to be extremely careful, when constructing a Mat like this.

what you've got there, is called a borrowed pointer, the memory does not get copied (only the pointer), thus, when the original pointer goes out of scope (e.g. when you leave that function), it is invalid !

though Mat is usually refcounted, and thus safe to return from a function (or to pass by reference to others) this is an exception to the rule. since it does not "own" the memory, there is no refcounting in this case.

there are a couple of solutions:

  1. clone it (make a deep copy): copy, then you also got proper refcounting again):

    return cv::Mat(2, 2, CV_64FC1, matrix).clone();

  2. use Matx class:

    Matx22d m(1,0,1,0); return m;

  3. use Mat_<double> and the << operator:

    Mat_<double> m(2,2); m << 1,0,1,0; return m;

  4. don't make it a (seperate) function. as long as your initialization and usage stays in the same scope, you're safe.