c++ - VS 2010 中 C++ 中的 static_cast 无法从 void* 转换为 size_t 错误

标签 c++

我有以下代码,但出现以下错误

error C2036: 'void *' : unknown size
error C2440: 'static_cast' : cannot convert from 'void *' to 'size_t'

在线

void *addr = static_cast <void*> (static_cast <size_t> (mem + bytesAlreadyAllocated));

我的问题是为什么会出现上述错误以及如何消除这些错误?

感谢您的帮助。

class MemoryChunk {
public:
    MemoryChunk (MemoryChunk *nextChunk, size_t chunkSize);
    ~MemoryChunk() {delete mem; }

    inline void *alloc (size_t size);
    inline void free (void* someElement);

    // Pointer to next memory chunk on the list.
    MemoryChunk *nextMemChunk() {return next;}
    // How much space do we have left on this memory chunk?
    size_t spaceAvailable() { return chunkSize - bytesAlreadyAllocated; }

    // this is the default size of a single memory chunk.
    enum { DEFAULT_CHUNK_SIZE = 4096 };
private:

    // The MemoryChunk class is a cleaner version of NextOnFreeList. It separates the next pointer from
    // the actual memory used for the allocated object. It uses explicit next and mem pointers, with no 
    // need for casting.

    MemoryChunk *next;
    void *mem;

    // The size of a single memory chunk.
    size_t chunkSize;
    // This many bytes already allocated on the current memory chunk.
    size_t bytesAlreadyAllocated;
};

MemoryChunk::MemoryChunk(MemoryChunk *nextChunk, size_t reqSize) {
    chunkSize = (reqSize > DEFAULT_CHUNK_SIZE) ? reqSize : DEFAULT_CHUNK_SIZE;
    next = nextChunk;
    bytesAlreadyAllocated = 0;
    mem = new char [chunkSize];
}

void* MemoryChunk :: alloc (size_t requestSize) {
    void *addr = static_cast <void*> (static_cast <size_t> (mem + bytesAlreadyAllocated));
    bytesAlreadyAllocated += requestSize;
    return addr;
}

inline void MemoryChunk :: free (void *doomed) {}

最佳答案

表达式:

static_cast <size_t> (mem + bytesAlreadyAllocated)

使用未定义大小的类型 (void) 应用偏移量。由于 void 没有大小,程序的格式不正确。

char* 是适合您在此场景中使用的指针。例如:

`char* mem;`
 // and
 char* addr(mem + bytesAlreadyAllocated);

更新

所以在下面的程序中:

#include <iostream>

int main(int argc, const char* argv[]) {
    const int array[3] = {-1, 0, 1};
    std::cout << *(array + 0) << ", "
      << *(array + 1) << ", " << *(array + 2) << "\n";
    return 0;
}

输出为 -1, 0, 1。根据数组元素的大小和类型应用元素偏移量。使用 void -- 大小不正确。

关于c++ - VS 2010 中 C++ 中的 static_cast 无法从 void* 转换为 size_t 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10381558/

相关文章:

c++ - 在至少访问 X 节点一次的图中查找最短路

c++ - uint8_t 乘以 boolean 值的类型是什么?

c++ - std::pow 不返回预期的 int 值

c++ - 在Visual Studio 2019上设置gmock的问题

c++ - 如何使用 OpenCV 图像蒙版

c++ - 使用 RapidXML 和 C++ 从 XML 文件构建树

c++ - 默认构造函数全部封装在头文件中

c++ - 使用 C/C++ 通过管道向/从 Powershell 设置 UTF-8 输入和获取 UTF-8 输出

c++ - 将异步操作的处理程序绑定(bind)到另一个类的非静态成员

c++ - 调用专门未模板化的函数