我维持旧的C++应用程序,其具有如下面很多类:紧凑矢量小的存储器脚印矢量
class ClassWithALotOfVectors
{
std::vector<int> _vector1;
std::vector<int> _vector2;
// a lot of other vector datamembers go here
std::vector<double> _vectorN;
};
那就是 - 一个数据类型,其中成员的载体双或者int。 的关键是 - 这些载体是从来没有填充在同一时间 - 因此 当我们创建ClassWithALotOfVectors 100000个实例 - 内存使用量增加了 令人印象深刻的数字,即使只有10%,这些载体都在使用。
所以我决定写一个小的“按需分配”矢量类。
它周围的std ::向量的包装 - 其中内部向量仅创建时 首次访问(使用两个吸气剂 - REF()& const_ref()方法)
当我取代的std ::向量在ClassWithALotOfVectors类,如下一个compact_vector :
class ClassWithALotOfVectors2
{
compact_vector<int> _vector1;
compact_vector<int> _vector2;
compact_vector<double> _vectorN;
};
做了一些测试,结果是有希望的 - 内存使用量下降 显着,却突然发现,应用程序不释放内存 在最后 - 内存消耗增长的速度远远低于它以前的 - 但应用程序似乎并没有在最后解除分配内存 。
你可以看一下我的执行compact_vector ,看看你是否能发现什么毛病内存管理。
template <class T> class compact_vector
{
public:
compact_vector<T>()
:_data(NULL)
{
}
~compact_vector<T>()
{
clear();
}
compact_vector<T>(const compact_vector<T> & rhs)
:_data(NULL)
{
if (NULL != rhs._data)
{
_data = new std::vector<T>(*(rhs._data));
}
else
{
clear();
}
}
// assignment
//
compact_vector<T> & operator=(const compact_vector<T> & rhs)
{
if (this != &rhs)
{
clear();
if (NULL != rhs._data)
{
_data = new std::vector<T>(*rhs._data);
}
}
return *this;
}
compact_vector<T> & operator=(const std::vector<T> & rhs)
{
clear();
if (!rhs.empty())
{
_data = new std::vector<T>(rhs);
}
return *this;
}
const std::vector<T> & const_ref()
{
createInternal();
return *_data;
}
std::vector<T> & ref()
{
createInternal();
return *_data;
}
void clear()
{
if (NULL != _data)
{
_data->clear();
delete _data;
_data = NULL;
}
}
private:
void createInternal()
{
if (NULL == _data)
{
_data = new std::vector<T>();
}
}
private:
compact_vector<T>(const std::vector<T> & rhs)
{
}
compact_vector<T>(std::vector<T> & rhs)
{
}
compact_vector<T>(std::vector<T> rhs)
{
}
std::vector<T> * _data;
};
你'clear'方法可以大大简化为'删除_data; _data = 0;' – 2012-03-19 11:16:34
如果可能,你应该使用'nullptr',尽管'NULL'仍然可以。 – leftaroundabout 2012-03-19 11:19:49
[stack exchange](http://stackexchange.com/)有一个[code review](http://codereview.stackexchange.com/)部分 – 2012-03-19 11:28:03