オブジェクトが破棄されると、バッファのメモリの割り当てを解除する必要があります。
void myfunc() {
Buffers::MyBuffer buf; // this create your object on stack
const char* data= new char[100];
datalen= readSomeData( data, 100 ); // not best for file, socket, etc.
buf.ParseFromArray(data, datalen); // this alocate any needed object
// by calling Buffers::SomeInternalBuffer:New
// now you may delete the data varible, is not needed
delete[] data; // called new, so call delete
...
buf.Clear(); // here the read data are lost,
// but some objects may not be deleted for future use
buf.mutable_someinternalbuffer(); // call Buffers::SomeInternalBuffer:New,
// or may not if ParseFromArray already call it
...
return; // here buf is out of scope and destroyed
// any buffers that are created by New is going to be deleted
}
release_foo バッファが削除されないようにするには、静的な New メソッドを使用します。
Buffers::MyBuffer* myfunc2() {
Buffers::MyBuffer* buf = Buffers::MyBuffer:New();
if( buf->ParseFromArray(data, datalen) )
return buf; // return object, no memory dealocation
delete buf; // something wrong with data, delete, destroy and dealocate
return NULL; // return null
}
メソッドを使用せSomeInternalBuffer
ずに保持する必要がある場合:MyBuffer
release_<field>
Buffers::SomeInternalBuffer* myfunc3() {
Buffers::MyBuffer buf; // this create your object on stack
if( buf.ParseFromArray(data, datalen) )
return buf.release_someinternalbuffer(); // return object
// if ParseFromArray do not call New, method release_someinternalbuffer
// will call New and copy data from default value
// no memory deallocation for returned object, everything else will deallocate
return NULL; // same as in first example
}