message LongUserIdSeqIdMapData {
map<int64, int32> userid_seqid = 1;
map<int32, int64> sedid_userid = 2; }
void GetUserIdSeqId(const std::string &user_id_seq_id_file) {
std::ifstream infile(user_id_seq_id_file);
infile.seekg(0, infile.end);
size_t length = infile.tellg();
infile.seekg(0, infile.beg);
auto *buffer = new char[length];
infile.read(buffer, length);
auto long_user_id_seq_id_map = new com::jaymz::poseidon::LongUserIdSeqIdMapData::LongUserIdSeqIdMapData();
if (!(*long_user_id_seq_id_map).ParseFromArray(buffer, length)) {
std::cout << "Parse user_id_seq_id_file Fail, Please Check Your File!" << std::endl;
} else {
std::cout << "Parse user_id_seq_id_file Success" << std::endl;
}
delete[] buffer;
delete long_user_id_seq_id_map;
}
我先将LongUserIdSeqIdMapData数据写入文件,然后通过调用函数GetUserIdSeqId从文件中解析它,我发现程序在执行GetUserIdSeqId时占用了190M物理内存,但是执行完GetUserIdSeqId后,程序仍然占用190M物理内存,因为没有内存被释放,我不知道为什么。
最佳答案
C++中有一个释放内存的函数:
google::protobuf::ShutdownProtobufLibrary();
Shut down the entire protocol buffers library, deleting all static-duration objects allocated by the library or by generated .pb.cc files.
There are two reasons you might want to call this:
- You use a draconian definition of "memory leak" in which you expect every single malloc() to have a corresponding free(), even for objects which live until program exit.
- You are writing a dynamically-loaded library which needs to clean up after itself when the library is unloaded.
It is safe to call this multiple times. However, it is not safe to use any other part of the protocol buffers library after ShutdownProtobufLibrary() has been called.
这应该可以解决您的问题!
关于c++ - 如何释放 Protocol Buffer 内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50414346/