dimanche 20 décembre 2020

arithmetic std::unique_ptr and void* (get position of element by address)

I have a class:

  1. Allocate blockSize*maxSize bytes of memory. Has a method which return ptr to free block of memory.
  2. I fill this block in main() for example (see usage below) and send it back to my class.

PROBLEM: How can I get position of sent me back address of initialized data? Because in main() I have void* ptr, not std::unique_ptr, and arithmetic with method memoryPool.get() not possible to use.

class A {
private:
    size_t maxBlocks;
    size_t blockSize;
    std::unique_ptr<unsigned char[]> memoryPool;

    void *getObjPtr(const size_t pos) const {
        return reinterpret_cast<void *>(memoryPool.get() + pos * blockSize);
    }
    
public:
    A(size_t blockSize, size_t maxBlocks) : blockSize(blockSize), maxBlocks(maxBlocks),
                                            memoryPool(new unsigned char[maxBlocks * blockSize]) {}

    void *getFree() {
        for (size_t i = 0; i < maxBlocks; ++i) {
            //check if this block not use (I cut this part)
            return getObjPtr(i);
        }
    }

    size_t getPosition(void *data) {
        //how can I get position of element? 
        // auto pos = ((char*)data - memoryPool.get()) / blockSize; - not works
        // ok there should be C++ style reinterpret_cast, but to short code I skip it
    }
}

Example of usage:

int main() {
    A queue(sizeof(int), 10);

    int *a = static_cast<int *>(queue.getFree());
    *a = 4;
    auto pos = queue.getPosition(a);//want to get position
}

What is proper way to do it? Without using std::unique_ptr in main?

Aucun commentaire:

Enregistrer un commentaire