lundi 1 octobre 2018

How to design smart pointer of array type in C++11


This is a class which contains image data.

class MyMat
{
public:
    int width, height, format;
    uint8_t *data;
}

I want to design MyMat with automatic memory management. The image data could be shared among many objects. Common APIs which I'm going to design:

+) C++ 11

+) Assignment : share data

MyMat a2(w, h, fmt);
.................
a2 = a1; 

+) Accessing data should be simple and short. Can use raw pointer directly.

In general, I want to design MyMat like as OpenCV cv::Mat

Could you suggest me a proper design ?

1) Using std::vector<uint8_t> data
I have to write some code to remove copy constructor and assignment operator because someone can call them and causes memory copy. The compiler must support copy ellision and return value optimization. Always using move assignment and passing by reference are inconvenient

a2 = std::move(a1)
void test(MyMat &mat)
std::queue<MyMat> lists;
lists.push_back(std::move(a1))
..............................

2) Use share_ptr<uint8_t> data
Following this guideline http://www.codingstandard.com/rule/17-3-4-do-not-create-smart-pointers-of-array-type/, we shouldn't create smart pointers of array type.

3) Use share_ptr< std::vector<uint8_t> > data
To access data, use *(a1.data)[0], the syntax is very inconvenient

4) Use raw pointer, uint8_t *data
Write proper constructor and destructor for this class. To make automatic memory management, use smart pointer.

share_ptr<MyMat> mat
std::queue< share_ptr<MyMat> > lists;

Aucun commentaire:

Enregistrer un commentaire