Search code examples
c++arraysprivate

C++ Private Array Access


I have a class that has a private unsigned char * to a data buffer. The data buffer can be of varaible length, so I use malloc() and free() to allocate the amount of memory I need to hold the data.

My problem is that I have another class that needs to access this data. The way I'm currently doing so is by creating a working copy of the buffer and passing that into the other class. That is, I have a function get_data(unsigned char * copy, int size) that copies size bytes into the buffer specifed by copy. The buffer is small (~50 bytes), but I have to do this ALOT over the course of my program. As a result, I'm looking for a way that I can make this more streamlined.

Is there a way that I can pass the data buffer pointer to any other classes? Will they be able to overwrite the data in the buffer? I'm aware that I can send back a const copy of the data buffer pointer, but the caller can then call const_cast and modify it at will. That is, they can call const_cast and then something along the lines of buf_ptr[2] = 0xFF;

Thanks in advance for the help. I'm hoping that there is a way I can just use the pointer without the possiblity of a caller to corrupt the data if they do something nasty.


Solution

  • Just provide a const unsigned char * accessor:

    const unsigned char * MyClass::get_buffer() const { return m_private_buffer; }
    

    Sure, there is a chance that someone using the buffer might decide to const_cast and modify it, but that's not your problem. That's them doing something that they know is naughty. And indeed, if you are the one writing all the code, then why on earth would you try to break it?