Problem of Hard Copy

    • Frequently allocate and free memory.
    • Time consuming when the memory is big.

    But…

    • If several objects share the same memory, who should release it?

    image.png
    image.png
    UMatData* u 就是存储引用的,存储data被多少对象引用。

    image.png Solution in OpenCV
    modules/core/src/matrix.cpp
    - The allocated memory can be used by multiple object
    - Mat::u->refcount is used to count the times the memory is referenced
    - CV_XADD: macro for atomic add

    image.png Copy constructor of cv::Mat
    modules/core/src/matrix.cpp
    image.png modules/core/src/matrix.cpp

    调用一次释放函数,引用计数-1,直到最后一个引用,然后释放掉该对象的内存空间,至此多个对象引用同一块内存地址的问题得以解决。