내가하려는 것은 클래스 객체를 버퍼에 배치 한 다음 나중에 올바르게 참조 할 수있게하는 것입니다. 기본적으로 데이터 저장을위한 버퍼. 내가 생각한 가장 좋은 방법은 객체의 주소를 버퍼에 저장하고 인덱스로 참조한 다음 캐스팅하는 것이 었습니다. 객체가이 메소드에서 로컬로만 살아 있고 로컬 객체의 주소가 반환되기 때문에 메모리 누출이 남을 수 있습니다. 내가 버퍼에 객체를 저장할 수있는 방법이 있고 나중에 과부하 연산자 [] Foo [index]를 호출하여 올바르게 참조 할 수 있습니까? C++: Casting an Object to char* for saving/loading과 동일한 기술을 사용해 보았지만 정적/재 해석 캐스트가 내 경우 버퍼에서 내용을 검색 할 때 주소 값을 변경하려고하는 경향이 있습니다.char * 버퍼에 클래스 객체 저장 및 버퍼에서 객체 참조
ps. 나는 벡터를 사용하는 것이 클래스 객체를 저장하는 더 쉬운 방법이 될 것이지만 제한의 일부는 데이터 저장을 위해 STL을 사용할 수없고 나에게 주어진 버퍼에 의존해야한다는 것이다.
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는 = 사용자 정의 클래스 객체 때 나는 문제가 올 것 :
#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
원래 나는 다음과 같은 추가 기능을하려고했다.
합니다. 당신이 찾고있는 것은 직렬화입니다. –
@ g-makulik이 경우 직렬화의 예를들 수 있습니까? 나는 많은 serialization을하지 않았으며 모든 예제가 도움이 될 것입니다. – hellfiremarine
넓은 분야입니다. Joachim Pileborg의 답변 링크부터 시작할 수 있습니다. Boost는 직렬화 라이브러리를 제공하지만 [s11n] (http://s11n.net/)은 또 다른 것입니다. 또한 직렬화 [placement new] (http://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new)가 사용자가 찾고자하는 것일 수도 있습니다 (사용 사례에 따라 다름). –