Home > OS >  Convert unsigned char* to std::shared_ptr<std::vector<unsigned char>>
Convert unsigned char* to std::shared_ptr<std::vector<unsigned char>>

Time:10-12

I'm trying to change a variable of type unsigned char* to std::shared_ptr<std::vector<unsigned char>> for memory management. The thing is, this code was written by a coworker who left several years ago, and I'm not so sure how to manage the change in some methods since I'm not familiar with them. Currently, I'm stuck with this function to get the buffer of an image from the class BaseImage.

const unsigned char* BaseImage::getConstBuffer() const
{
    if(m_bufferSize == 0) return 0;
    else return m_bufferData   m_headerSize;
}

With:

unsigned int m_bufferSize;
unsigned short m_headerSize;
unsigned char* m_bufferData = new unsigned char[(unsigned) m_headerSize   m_bufferSize];

I'm not sure to understand why we are adding m_bufferData to m_headerSize, and what would be the proper way to change it after the conversion. Does anyone have an idea?

CodePudding user response:

Just to explain the existing code: It's doing some pointer arithemtics here, and returning the starting address for the data section of your buffer (skipping the header section). The naming is a little inconsistent here between Buffer and Data.

Is this high performance code ? If not, i'd probably just keep Header and Data separated in their own std::vector and maybe return them as a std::pair for accessing.

CodePudding user response:

If you really need the callers of this function to share ownership of the return value, then you can use std::shared_ptr<unsigned char[]>. Much more likely, callers only get to observe the pointed to data, and don't need to own it. In that case, you can use std::vector<unsigned char> as the data member, and continue to return unsigned char*.

class BaseImage
{
    unsigned short m_headerSize;
    std::vector<unsigned char> m_bufferData;
public:
    BaseImage(size_t bufferSize, unsigned short headerSize) : m_headerSize(headerSize), m_bufferData(bufferSize   headerSize) {}

    const unsigned char* BaseImage::getConstBuffer() const
    {
        if(m_bufferData.size() == m_headerSize) return nullptr;
        else return m_bufferData.data()   m_headerSize;
    }
};
  • Related