class CollectNetCardInfo{
public://define
#define SAFE_DELETE(p) {delete p;p=NULL;}public:
CollectNetCardInfo();
~CollectNetCardInfo();
void ReleaseMemory(map<int ,BYTE*> mapItems);
public://Ver
map<int ,BYTE*> m_NetCardDesMap;
//这里有很多 map<int ,BYTE*> 类型的变量
map<int ,BYTE*> m_FriendlyName;
map<int ,BYTE*>::iterator m_MapIt;//---------------1
};
CollectNetCardInfo::~CollectNetCardInfo()
{
//回收map中BYTE*内存
ReleaseMemory(m_NetCardDesMap);
//这里要调用很多次
ReleaseMemory(m_FriendlyName);
}
void CollectNetCardInfo::ReleaseMemory(map<int ,BYTE*> mapItems)
{
if(!mapItems.empty())
{
map<int ,BYTE*>::iterator It = mapItems.begin();//------------------2
// m_MapIt = mapItems.begin();----------------------------------------3
while(It != mapItems.end())
{
SAFE_DELETE(m_MapIt->second);
It++;
}
}
}上面代码中类的方法ReleaseMemory中在回收内存中有2和3两种做法:2 是在方法ReleaseMemory中定义一个局部变量It,用它来遍历传进来的map。
3 是通过类中定义的m_MapIt变量来遍历传进来的map。2 和3用哪个比较好?说明:类中map<int ,BYTE*> 类型的成员变量比较多,因此ReleaseMemory也要被调用很多次。
代码是为了描述问题,至于map中BYTE* 是在哪里分配的这些大家都不用管。
public://define
#define SAFE_DELETE(p) {delete p;p=NULL;}public:
CollectNetCardInfo();
~CollectNetCardInfo();
void ReleaseMemory(map<int ,BYTE*> mapItems);
public://Ver
map<int ,BYTE*> m_NetCardDesMap;
//这里有很多 map<int ,BYTE*> 类型的变量
map<int ,BYTE*> m_FriendlyName;
map<int ,BYTE*>::iterator m_MapIt;//---------------1
};
CollectNetCardInfo::~CollectNetCardInfo()
{
//回收map中BYTE*内存
ReleaseMemory(m_NetCardDesMap);
//这里要调用很多次
ReleaseMemory(m_FriendlyName);
}
void CollectNetCardInfo::ReleaseMemory(map<int ,BYTE*> mapItems)
{
if(!mapItems.empty())
{
map<int ,BYTE*>::iterator It = mapItems.begin();//------------------2
// m_MapIt = mapItems.begin();----------------------------------------3
while(It != mapItems.end())
{
SAFE_DELETE(m_MapIt->second);
It++;
}
}
}上面代码中类的方法ReleaseMemory中在回收内存中有2和3两种做法:2 是在方法ReleaseMemory中定义一个局部变量It,用它来遍历传进来的map。
3 是通过类中定义的m_MapIt变量来遍历传进来的map。2 和3用哪个比较好?说明:类中map<int ,BYTE*> 类型的成员变量比较多,因此ReleaseMemory也要被调用很多次。
代码是为了描述问题,至于map中BYTE* 是在哪里分配的这些大家都不用管。
class mymap : public map<int, BYTE*>
{
public:
~mymap()
{
// release memory here
}
};
虽然也能够Delete掉Map的元素,但都是因为默认拷贝构造的原因。
最好使用引用传递。
同意楼上几位的,不建议使用类变量,除非有特殊需要。另外就是,还可以使用如下方式来使用Map:
typedef map<int ,BYTE*> Int2BytePointerMap;Int2BytePointerMap m_FriendlyName;
这样你参数传递的时候,就能使用Typedef定义的别名。
这段代码问题多多啊
而且带来的性能上的代价应该很小,除非你这块代码的性能要求极高。
我想ReleaseMemory()要调几十次的情况下,两种方式的性能差异应该不大