我想使用std::shared_ptr
和std::list
处理我的问题(内存限制),请注意我需要与一些需要原始指针的遗留C代码接口,我的主要目标是有一种动态内存管理(可以随时回收内存),我的psudo代码如下,
// 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
}
所以,我的问题是,
答案 0 :(得分:1)
你不能这样做:
std::list< std::vector<data_type> > dynamic_storage;
然后去:
dynamic_storage.move_back( std::move( std::vector<data_type>(N) );
当你需要一个指针时,使用迭代器或你的方法:
data_type* p = &dynamic_storage.back()[0];
然后整个事情应该在超出范围时清理,这样你就不需要任何特定的清理代码了......