我想爲我的問題(內存綁定)使用std::shared_ptr
和std::list
在處置,請注意,我需要與一些傳統的C代碼,需要原始指針和我的主要目標是讓一種動態內存管理的(可以回收內存只要有可能),我psudo-代碼之後,內存管理與std :: list和std :: shared_ptr
// My "central" storage
typedef std::shared_ptr<double> data_type;
std::list<data_type> dynamic_storage;
// At each allocation point
dynamic_storage.push_back(data_type());
dynamic_storage.back.reset(new double[N],std::default_delete<double[]>());
// immediately after each allocation, store the shared_ptr to some map
std::map<data_type> map_for_job1; // may have several maps
int index; // unique index for later access, related to domain-specific problem
data_type ptr_in_map(dynamic_storage.back()); // reference counter +1
map_for_job1[index]=ptr_in_map; // store in map
// when I want to access again with a certain map and index
double *raw_data = map_for_job1.find(index).get();
// when I'm done with all the resources shared by buffer_map_1
map_for_job1.clear(); // reference counter -1
for (std::list<data_type>::iterator it=dynamic_storage.begin(); it != dynamic_storage.end(); ++it)
{
if (*it.use_count()==1)
dynamic_storage.erase(i) // release resource from central storage
}
所以,我的問題是,
- 這是一個有效的內存管理模式?
- 如何改進,也許遍歷列表太昂貴了?
有多種內存管理模式,所以沒有真正的「有效」你有沒有考慮[使用現有的](http://stackoverflow.com/questions/1194479/write-your-own-memory-manager)? –