*(void **)的含义是什么

时间:2014-02-08 02:23:48

标签: c++ void

我在互联网上看过这样的课程, 头文件

#ifndef _COMMON_ARRAY_OBJECT_POOL_H_
#define _COMMON_ARRAY_OBJECT_POOL_H_

#include <stdint.h>

namespace easynet
{

class ArrayObjectPool
{
public:
    /** construct
     * @param elem_size : element size;
     * @param elem_num  : element number
     */
    ArrayObjectPool(uint32_t elem_size, uint32_t elem_num);
    ~ArrayObjectPool();

    uint32_t ElemSize(){return m_ElemSize;}
    uint32_t Capacity(){return m_ElemNum;}
    bool IsEmpty(){return m_FreeHead==NULL;}


    void* Get();


    bool Recycle(void *elem);
private:
    void *m_Elements;
    void *m_End;
    void *m_FreeHead;
    uint32_t m_ElemSize;
    uint32_t m_ElemNum;
};

}
#endif //_COMMON_ARRAY_OBJECT_POOL_H_

cpp文件

#include <assert.h>
#include <stddef.h>
#include <stdlib.h>

#include "ArrayObjectPool.h"

namespace easynet
{

ArrayObjectPool::ArrayObjectPool(uint32_t elem_size, uint32_t elem_num)
{
    m_ElemNum = elem_num;
    if(elem_size < sizeof(void*))
        m_ElemSize = sizeof(void*);
    else
        m_ElemSize = elem_size;

    m_Elements = malloc(m_ElemSize*m_ElemNum);
    m_End = (void*)((char*)m_Elements+m_ElemSize*m_ElemNum);
    assert(m_Elements != NULL);

    //construct list
    int i;
    void *node = m_Elements;
    for(i=0; i<m_ElemNum-1; ++i)
    {
        *(void**)node = (void*)((char*)node+m_ElemSize);
        node = *(void**)node;
    }
    *(void**)node = NULL;
    m_FreeHead = m_Elements;    //list head
}

ArrayObjectPool::~ArrayObjectPool()
{
    free(m_Elements);
}

void* ArrayObjectPool::Get()
{
    if(m_FreeHead == NULL)
        return NULL;
    void *temp = m_FreeHead;
    m_FreeHead = *(void**)m_FreeHead;
    return temp;
}

bool ArrayObjectPool::Recycle(void *elem)
{
    if(elem<m_Elements || elem>=m_End)
        return false;
    *(void**)elem = m_FreeHead;
    m_FreeHead = elem;
    return true;
}

}

问题是我无法理解这意味着什么:

int i;
void *node = m_Elements;
for(i=0; i<m_ElemNum-1; ++i)
{
*(void**)node = (void*)((char*)node+m_ElemSize);
node = *(void**)node;
}

以及*(void**)的含义是什么?谢谢!

2 个答案:

答案 0 :(得分:2)

它将内存视为用户数据类型与union之间的void*。当块在空闲块列表中时,使用void*

您可以将其视为:

union ObjectInObjectPool
{
    void* ptr_next_free_block;
    UserType content;
};

然后该循环基本上正在做:

ObjectInObjectPool* node = m_Elements;
for(i=0; i<m_ElemNum-1; ++i) {
    node->ptr_next_free_block = node + 1;
    node = node->ptr_next_free_block;
}

除了程序员手工完成编译器的类型检查器通常所做的所有指针算法。

答案 1 :(得分:0)

void*是指向无类型内存的指针值。当你*(void**)node = ...时,它真正做的是*node = ...。但是,对于后者,你试图给void赋予一些东西,这对C ++的类型系统没有意义;你必须像前者一样把它投射到void**,这样*node将是void*,而不是void,你可以分配给它。 / p>

node = *(void**)node只是node = *node,但强制类型系统正常工作。它只是“node*node内存的值分配为void*”。