我正在尝试实现一个自定义内存管理器,我想知道是否有更好的方法来实现这个函数,因为当我被问及无效指针算术时,有些人认为如果我在C++中有一个void*,那就非常错误.
// allocates a page of memory.
void ObjectAllocator::allocatePage()
{
//if(OAStats_.PagesInUse_ >= Config_.MaxPages_)
//throw exception
void* buffer = ::operator new(OAStats_.PageSize_); // allocate memory, no constructor call.
// =============== Setup the PageList_ ===============
GenericObject* pNewNode = ::new(buffer) GenericObject(); // Construct GenericObject for the pagelist.
pNewNode->Next = PageList_->Next; // pNewNode points to wherever PageList_ pointed to.
PageList_->Next = pNewNode; // PageList_ points to pNewNode
pNewNode = NULL; // dont need this handle anymore
buffer = static_cast<char*>(buffer) + sizeof(GenericObject); // move pointer to …Run Code Online (Sandbox Code Playgroud) 在Visual Studio C++版本9(也可能是其他版本)中,以下代码:
int a = sizeof(void);
void const *b = static_cast<void const *>("hello world");
b += 6;
Run Code Online (Sandbox Code Playgroud)
error C2070: 'void': illegal sizeof operand
error C2036: 'const void *' : unknown size
Run Code Online (Sandbox Code Playgroud)
此代码在GCC下工作,GCC sizeof(void)视为1.
是否存在一些解决此限制的方法,因为char *为了指针运算的目的而明确地进行转换会增加混淆(void *被公认并被用作原始内存的无类型指针).
sizeof(void)认为我很清楚这不是1导致问题的原因.void,但这是C,这些事情都会发生.看来这个问题引起了很大的混乱.现在的问题不是关于为什么有sizeof(void) == 1不标准,但做什么时,它不是.
在要进行单字节指针运算的情况下,事实证明,转换为char *正确的答案,不是因为*(void *)没有大小,而是因为标准实际上保证了这*(char *) …
如何以单字节精度可移植地执行指针运算?
请记住:
char 在所有平台上都不是1个字节sizeof(void) == 1 仅作为GCC的扩展名提供c compiler-construction portability void-pointers pointer-arithmetic