【问题标题】:static_cast cannot convert from void* to size_t error in C++ in VS 2010VS 2010 中的 C++ 中的 static_cast 无法从 void* 转换为 size_t 错误
【发布时间】:2012-04-30 09:46:09
【问题描述】:

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

错误 C2036:'void *':未知大小
错误 C2440:“static_cast”:无法从“void *”转换为“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) {}

【问题讨论】:

  • 你忘了问问题。你想解释错误吗?你想要一个解决方法吗?您想知道错误信息是否正确,或者您的代码是否合法?
  • 这并不是您问题的真正答案,但我认为您可以通过以下方式完成: void *addr = static_cast(static_cast(mem) + bytesAlreadyAllocated) .
  • 是的。将整数添加到 void * 是未定义的行为。
  • 转换为 char * 然后添加偏移量。
  • 编译器抱怨的原因是您不能从指针 (void *) 向上转换为 size_t,因为一个不是另一个的子类型。为此,您必须使用 C 风格的未经检查的强制转换。

标签: c++


【解决方案1】:

表达式:

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 -- 大小不合适。

【讨论】:

  • 是的。 5.7 列出了您可以添加到指针的所有法律案例。这不是其中之一。
  • 你能详细说明一下吗?我是 C++ 类型转换的新手。谢谢!
  • @venkysmarty 我扩展以演示您将如何克服该问题。正在进行另一个更新......
猜你喜欢
  • 1970-01-01
  • 2014-09-13
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
相关资源
最近更新 更多