Ege Yıldırım
Ege Yıldırım

Reputation: 435

OpenCV Should I use smart pointers to prevent memory leak

i have a OpenCV program for preprocessing and detecting text area for OCR.

For example in this part of program:

    cv::Mat image;
    cv::Mat outImage;
    cv::Mat image_blurred_5x5_kernel;

    cv::resize(image, outImage, cv::Size(), .75, .75);
    cv::GaussianBlur(image, image_blurred_3x3_kernel, cv::Size(3, 3), 0);

The program creates 3 images; original, resized and blurred one. I'm only going to use the last image i acquired. For example after resizing the original image and storing it in some variable, i won't be using original image anymore.

but as you see i created and used objects themselves, i am wondering is using smart pointers would result in better memory control? Or destructors are enough for this and difference between two methods is negligible? Execution time is my priority, rather than space usage.

Upvotes: 2

Views: 521

Answers (1)

Mikael H
Mikael H

Reputation: 1383

cv::Mat is itself managing its resources, which will be released when the destructor is called. Since you put them on the stack, that will be handled automatically when you go out of scope.

You should use smart pointers if you were not putting the objects on the stack, i.e.

cv::Mat* image_ptr = new cv::Mat; // now you need to handle memory, since the allocated object will not be deleted automatically when changing scope
auto image_smart_pointer = std::make_unique<cv::Mat>(); // allocated object will be deallocated correctly when changing scope, since image_smart_pointer is destructed at change of scope.

Upvotes: 2

Related Questions