2

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. How to improve, perhaps traversing a list is too expensive?
seam
  • 43
  • 4
  • 1
    There's multiple memory management patterns, so there's not really any one `valid` one as such; have you considered [using an existing one](http://stackoverflow.com/questions/1194479/write-your-own-memory-manager)? – Luke Briggs Nov 24 '16 at 19:56

1 Answers1

1

Can't you simply do:

std::list< std::vector<data_type> > dynamic_storage;

And then go:

dynamic_storage.move_back( std::move( std::vector<data_type>(N) );

When you need a pointer, use iterator or as you did:

data_type* p = &dynamic_storage.back()[0];

Then the whole thing should clear up when falling out of scope so you don't need any particular cleanup code...

jaw
  • 31
  • 3
  • I would the list(the "central" storage) to keep the ownership, otherwise I can use std::unique_ptr and get raw pointer with .release() method. – seam Nov 24 '16 at 20:37
  • when you need to access a specific chunk through a raw pointer later after the initial allocation, it's not always on the back! So some indexing is used in OP's post. – lorniper Nov 24 '16 at 22:42