this function allocates new memory by first creating a new cv::Mat object on heap (just some bytes for the Mat header)
The reference counting is very nice and you typically don't use things like int or std::vector or std::string as pointers ) cv::Mat* MatPointerReturningFunc() But even better it is to not use Pointers for cv::Mat objects, because it is much less error prone and there isn't much overhead. Important to mention that the "best" way of using Pointers are often smart pointers, which are explicitly given by OpenCV.
#Freemat error deletion code
Here is some sample code with 2 different Mat Ptr returning functions and some ways to access them with or without leaking. Try cv::Mat * returnedPtr = MatPointerReturningFunc(.) followed by cv::Mat * m = new cv::Mat(*returnedPtr) if you want to create a new Mat object (or just use the returnedPtr without creating new). More concrete, Mat* m = new Mat ( *MatPointerReturningFunc(.)) will create a new cv::Mat object which is ok because you can delete it later, BUT the pointer which is returned by the function is lost. So short: For every new cv::Mat there must be a delete, so if there is a new in the external function, maybe you have to call a delete for it (if the function does not do it by some smart class functionality itself later). If that is not the case, the reference counting of the cv::Mat pixel data will not work as expected and in addition, some (minor) memory will be leaked by the cv::Mat objects themselves.
In your sample code it is not clear whether the objects, whose pointers are returned in the functions, will be deleted anywhere. It is definitely possible to work with cv::Mat pointers, but (as with all pointers) you have to take extra care of deleting the created objects to give allocated memory free again.