简体   繁体   English

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

[英]Storing a class object in a char * buffer and referencing the object from the buffer

What I am trying to do is to place a class object in the buffer and then be able to reference it correctly later.Essentially its a container class using a buffer for data storage.The best way I thought of doing so was storing the object's address in the buffer, reference it by its index, and then cast it. 我想做的是将一个类对象放在缓冲区中,然后以后可以正确地引用它。基本上是使用缓冲区进行数据存储的容器类,我想到的最好方法是存储对象的地址在缓冲区中,通过其索引引用它,然后对其进行强制转换。 I see now by doing it that way can potentially leave memory leaks because the object is only living locally in this method and the address of that local object is being returned. 我现在看到,通过这种方式可能会导致内存泄漏,因为该对象仅在本地驻留在此方法中,并且该本地对象的地址正在返回。 Is there a way I can store the object into the buffer and have it correctly referenced later by invoking overloaded operator[] Foo[index]? 有没有一种方法可以将对象存储到缓冲区中,并稍后通过调用重载的operator [] Foo [index]使其正确引用? I have tried using the same technique with C++: Casting an Object to char* for saving/loading but static/re-interpret cast in my case are tending to change the address values when I attempt to do an address look up for the contents in the buffer. 我已经尝试过使用与C ++相同的技术:将对象强制转换为char *以进行保存/加载,但是在我的情况下,静态/重新解释强制转换会在尝试查找地址中的内容时更改地址值。缓冲区。

ps. PS。 I know that using a vector would be an easier way of storing class objects but part of the restriction is that I can't use STL for data storage and have to rely on the buffer given to me. 我知道使用向量将是存储类对象的一种更简单的方法,但是部分限制是我不能使用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

Originally I was trying to do the add as follows: 最初,我尝试执行以下添加操作:

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;
    }

But I would come into problems when T = was a custom class object. 但是当T =是自定义类对象时,我会遇到麻烦。

You have undefined behaviors in your Add function, as first you store a pointer to a local variable (with oBuffer = (char*) nElement ), then with the same statement you overwrite the original pointer, which you already overwritten in the statement above, and then you return the address of the pointer (ie char ** ) but cast it as a single pointer. 您在Add函数中具有未定义的行为,因为首先存储指向局部变量的指针(使用oBuffer = (char*) nElement ),然后使用相同的语句覆盖了原始指针,而该原始指针已在上述语句中被覆盖,然后返回指针的地址(即char ** ),但将其强制转换为单个指针。

Your indexing function also will not work, as nIndex is the index in the char "array" and will not be the same unless the templated type T is char . 您的索引功能也将不起作用,因为nIndexchar “数组”中的索引,除非模板类型Tchar否则它将不相同。

If you want to store objects of a certain type, use std::vector . 如果要存储某种类型的对象,请使用std::vector

If you want serialization for saving to file/sending over network, it won't work either for any type containing pointer, collections, files etc. 如果要序列化以保存到文件/通过网络发送,则对包含指针,集合,文件等的任何类型都将无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM