将类对象存储在char *缓冲区中并从缓冲区引用该对象

时间:2013-09-04 06:28:08

标签: c++ buffer containers

我想要做的是将一个类对象放在缓冲区中,然后能够在以后正确引用它。实际上它是一个使用缓冲区进行数据存储的容器类。我想这样做的最好方法是存储缓冲区中的对象地址,通过索引引用它,然后转换它。我现在看到通过这样做可能会导致内存泄漏,因为该对象仅在本地居住在此方法中并且正在返回该本地对象的地址。有没有办法可以将对象存储到缓冲区中并通过调用重载的operator [] Foo [index]来正确引用它? 我尝试使用与C++: Casting an Object to char* for saving/loading相同的技术,但在我的情况下,静态/重新解释强制转换时,当我尝试查找缓冲区中的内容时,会更改地址值。

PS。我知道使用向量将是一种更容易存储类对象的方法,但部分限制是我不能使用STL进行数据存储,并且必须依赖于给我的缓冲区。

#include <stdlib.h>
#include <assert.h>
#ifndef FOO_H_
#define FOO_H_

template <typename T>
class Foo {
    char * oBuffer = NULL;
    unsigned items = 0, bSize = 0;
public:
    Foo(char * pBuffer, unsigned nBufferSize) :
        oBuffer(pBuffer),
        items(),
        bSize(nBufferSize){

        /*for (unsigned i =0; i < nBufferSize; i++)
            oBuffer[i] = &pBuffer[i];*/
    }
    ~Foo(){ delete[] oBuffer;}

    T * Add(){              ///======   Adds an element to the container, constructs it and returns it to the caller.
        assert(Capacity() > Count());
        T nObj; // new object
        T *nElement = &nObj; // address of new object
        oBuffer += items;    // incrementing pointer by item count    
            oBuffer = (char*) nElement; // attempt to store object address in buffer[items] location
        items++; // increment items count by one
        return (T*) &oBuffer;
    }

    T *  operator [] (unsigned nIndex){         ///======   Returns the n th element of the container [0..Count -1].
        return (T*) (&oBuffer[nIndex]);
    }

};

#endif

最初我尝试按以下方式添加:

T *  Add(){             ///======   Adds an element to the container, constructs it and returns it to the caller.
        assert(Capacity() > Count());
        T *add =&(oBuffer[items++] = T{});
        return add;
    }

但是当T =是自定义类对象时,我会遇到问题。

1 个答案:

答案 0 :(得分:1)

您的Add函数中有未定义的行为,首先您将指针存储到本地变量(使用oBuffer = (char*) nElement),然后使用相同的语句覆盖原始指针,您已在上面的语句中覆盖,然后返回指针的地址(即char **),但将其转换为单个指针。

您的索引功能也不起作用,因为nIndexchar&#34;数组&#34;中的索引。除非模板类型Tchar,否则不会相同。

如果要存储特定类型的对象,请使用std::vector

如果您希望serialization保存到文件/通过网络发送,它不会对包含指针,集合,文件等的任何类型工作。