c++ - 算术 std::unique_ptr 和 void* (通过地址获取元素的位置)
问题描述
我有一堂课:
- 分配 blockSize*maxSize 字节的内存。有一个方法可以返回 ptr 以释放内存块。
- 例如,我填写此块
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
主要?
解决方案
当我使用 Visual C++ 2019 编译您的代码时,我收到此错误:
error C2440: '-': cannot convert from 'unsigned char *' to 'char *'
如果我根据错误消息将您的代码更改为强制转换unsigned char*
,那么它会编译:
auto pos = ((unsigned char*)data - memoryPool.get()) / blockSize;
这是否符合您的意图 - 好吧,它似乎是,但您还没有明确指定做什么getPosition
,所以我只能猜测。
以后请把错误信息贴出来,不要光说不行!它会帮助我们帮助你。
推荐阅读
- java - 反序列化 json,将子类对象提升到顶层而不是嵌套类
- python-3.x - 特殊排序列数据框
- google-cloud-platform - 是否可以过滤 GCP Cloud SQL 复制中的某些列?
- r - 在 summarise_at() 中使用 n() 时出错
- java - 如何修复 JDBC 中的 SQLNonTransientConnectionException
- flask - 如何编写一个 api 来根据传递的索引获取表的记录?
- javascript - 如何在javascript中将此字符串“09-March-2018”转换为Unix时间戳?
- c# - 从基接口集合创建派生接口的通用集合
- laravel-6 - 未找到错误类“Illuminate\Support\Facades\Input” laravel v6.0.2
- openvino - OpenVINO 将 TF 模型转换为 IR 文件问题