vector new内存溢出 delete操作

我用vector容器存放结构体变量
如果你的结构体定义成这样
typedef struct A
{
A()
{
memset( this, 0, sizeof( A) );
}
A(const A& in)
{
memcpy( this, &in, sizeof( A) );
}
bool isSame(const A& in)
{
return strcmp( h, in.h) == 0;
}
bool isSame(const char* h, const char* c)
{
return ( strcmp( this->h, h) == 0 && strcmp( this->c, c) == 0 );
}

bool operator==(const A& in)
{
return ( strcmp( h, in.h) == 0 && strcmp( c, in.c) == 0);
}

bool operator!=(const A& in)
{
return !( *this == in );
}
char h[128];
char c[128];
int a;
std::vector<CString> w;
}A,*PA

类中
class B: public CDialog
{
public:
std::vector<PA> m_A;
}

.cpp

PA  p = new A;
m_A.push_back(p);

如果这是直接释放内存delete p;p=NULL;是不可以的;m_A.push_back(p);只是将p的指针传进容器中,是指向同一块内存的,
如果这时将p释放掉,那么容器指向的将是野指针

一个办法是在.h中再定义一个容器
std::vector<PA>   m_Point;
.cpp中每当new一个时就将他放进:
PA  p = new A;
m_Point.push_back(p);
m_A.push_back(p);
然后再~B中
PA pa = NULL;
while( m_Point.size() > 0 )
{
pa= m_Point.front();
if ( NULL != pa)
{
m_Point.erase( m_Point.begin() );
delete pa;
pa= NULL;
}
}
当然 你也可以就直接释放m_A,而不用存到m_Point中,如果遇到使用vector只是用作中间变量的话,就需要用到m_Point最后释放一下。

.h
struct A
{};
std::vector<A *> pPoint;
.cpp
A *pA=new A;
pPoint.push_back( pA );
析构
A *pA = NULL;
while( pPoint.size() > 0 )
{
pA = pPoint.front();
if ( NULL != pA )
{
pPoint.erase( pPoint.begin() );
delete pA;
pA = NULL;
}
}


刚刚学习,欢迎指教



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值