arithmetic std::unique_ptr 和 void* (通过地址获取元素的位置)
arithmetic std::unique_ptr and void* (get position of element by address)
我有一个 class:
- 分配 blockSize*maxSize 字节的内存。有一个方法 return ptr 来释放内存块。
- 例如,我在
main()
中填写此块(请参阅下面的用法)并将其发送回我的 class。
问题: 我怎样才能得到初始化数据的发回地址的位置?因为在 main() 中我有 void* ptr
,而不是 std::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
}
正确的做法是什么?在 main?
中不使用 std::unique_ptr
当我使用 Visual C++ 2019 编译您的代码时,出现此错误:
error C2440: '-': cannot convert from 'unsigned char *' to 'char *'
如果我根据错误消息将您的代码更改为 unsigned char*
,那么它会编译:
auto pos = ((unsigned char*)data - memoryPool.get()) / blockSize;
这是否符合您的意图 - 嗯,看起来是这样,但您没有明确说明 getPosition
的作用,所以我只能猜测。
以后请post报错信息,不要只说不行!它会帮助我们帮助你。
我有一个 class:
- 分配 blockSize*maxSize 字节的内存。有一个方法 return ptr 来释放内存块。
- 例如,我在
main()
中填写此块(请参阅下面的用法)并将其发送回我的 class。
问题: 我怎样才能得到初始化数据的发回地址的位置?因为在 main() 中我有 void* ptr
,而不是 std::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
}
正确的做法是什么?在 main?
中不使用std::unique_ptr
当我使用 Visual C++ 2019 编译您的代码时,出现此错误:
error C2440: '-': cannot convert from 'unsigned char *' to 'char *'
如果我根据错误消息将您的代码更改为 unsigned char*
,那么它会编译:
auto pos = ((unsigned char*)data - memoryPool.get()) / blockSize;
这是否符合您的意图 - 嗯,看起来是这样,但您没有明确说明 getPosition
的作用,所以我只能猜测。
以后请post报错信息,不要只说不行!它会帮助我们帮助你。