Chris Chris - 2 months ago 20x
C++ Question

OpenCV or Boost smart pointers

I have an expanding image processing project which relies heavily on the OpenCV library for much of its functionality, although I do also use a few boost functions as well.

I'd like to start using smart pointers to replace some raw pointers which are beginning to cause problems. My question is on which type of smart pointer to use, with my main choices (I think) being the OpenCV

or one of the boost variants.

I realise there are a number of questions explaining the different between each of the boost pointers, but I hoped somebody could offer an explanation of how
compares with them and make any recommendations of one or the other?

EDIT - I've noticed from the OpenCV docs that
is similar to boost
, is the essential difference just which library/include files are required?


For what I can see in OpenCV documentation, this is a reference-counted smart pointer, essentially, same as boost::shared_ptr. Even it uses atomic operations on the reference count.

I would make the choice based on portability and interoperability.

  1. Is your system going to be ported elsewhere and depends on OpenCV for sure but not on boost? Then, stick to OpenCV cv::Ptr if you can avoid boost and you get rid of the dependency.

  2. Does boost::shared_ptr plays nice with the rest of OpenCV? If you have something returning a cv::Ptr from OpenCV library, maybe it's better to stick to cv::Ptr in these cases, because the reference count will be handled incorrectly if you mix both kind of pointers and the resource could be destroyed prematurely.

  3. You're going to stick to boost wherever you port the project? Then, stick to boost::shared_ptr when you can do it, it's more standard, people know it and will immediately understand your code. NOTE: In C++11 you have std::shared_ptr, which amounts to no dependency if you can afford it, so you can use std::shared_ptr in this case and get rid of boost also.

Just as a side note, there is a technique to mix boost and std shared pointers that can keep the reference correctly around and could be useful for someone. See this question, it could be relevant also for mixing other kind of reference-counted pointers: Conversion from boost::shared_ptr to std::shared_ptr?

In my experience, when you port something, the fewer dependencies, the better, or there are certain platforms for which compiling can be a hell. So make your choice based on portability if it's a concern and interoperability of pointers with libraries.