2

我通过以下方式使用 Google 协议缓冲区:

void myfunc() {
    Buffers::MyBuffer buf;
    buf.ParseFromArray(data, datalen);
    ...
    return;
}

Protocol Buffers的文档说要为应该删除对象的缓冲区释放内存。我不是 C++ 天才,但我认为delete应该只为分配有new. 在这里返回时是否清理了内存?

4

1 回答 1

2

当对象被销毁时,应该释放缓冲区的内存。

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 要防止删除缓冲区,请使用静态新方法:

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
}
于 2012-04-18T20:49:58.523 回答