首页 > 解决方案 > 算术 std::unique_ptr 和 void* (通过地址获取元素的位置)

问题描述

我有一堂课:

  1. 分配 blockSize*maxSize 字节的内存。有一个方法可以返回 ptr 以释放内存块。
  2. 例如,我填写此块main()(请参阅下面的用法)并将其发送回我的班级。

问题:如何获取已初始化数据的发回地址的位置?因为在 main() 中,我有void* ptr、 notstd::unique_ptr和算术方法,memoryPool.get()无法使用。

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
    }
}

使用示例:

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
}

什么是正确的方法?不使用std::unique_ptr主要?

标签: c++c++11unique-ptr

解决方案


当我使用 Visual C++ 2019 编译您的代码时,我收到此错误:

error C2440: '-': cannot convert from 'unsigned char *' to 'char *'

如果我根据错误消息将您的代码更改为强制转换unsigned char*,那么它会编译:

auto pos = ((unsigned char*)data - memoryPool.get()) / blockSize;

这是否符合您的意图 - 好吧,它似乎是,但您还没有明确指定做什么getPosition,所以我只能猜测。

以后请把错误信息贴出来,不要光说不行!它会帮助我们帮助你。


推荐阅读