jeudi 24 novembre 2016

Memory management with list and std::shared_ptr

I want to use the std::shared_ptr and std::list for my problem(memory bound) at disposal, notice that I need to interface with some legacy C code that requires the raw pointers and my main objective is to have kind of dynamic memory management(can reclaim memory whenever possible), my psudo-code is following,

// 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
}

So, my questions are,

  1. Is this a valid memory-management pattern?
  2. Perhaps at some point I'm completely wrong? or how can I improve?

Aucun commentaire:

Enregistrer un commentaire