正确释放协议缓冲区内存

时间:2012-04-18 20:28:11

标签: c++ memory-management protocol-buffers

我正在以下列方式使用Google Protocol Buffers:

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

documentation for Protocol Buffers says为释放对象应该删除的缓冲区释放内存。我不是C ++天才,但我认为只应为delete分配的对象调用new。返回时是否清理了内存?

1 个答案:

答案 0 :(得分:1)

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

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
}