当类中包含STL容器成员时

来源:互联网 发布:vip域名备案的可能性 编辑:程序博客网 时间:2024/06/05 07:43
 最近为一个低级错误犯了一下午难。

student.h
class CStudent
{
public:
    
void    SetName(LPCTSTR lpszName);
    
void    SetAge(int iAge);

    LPCTSTR    GetName();
    
int        GetAge();
protected:
    TCHAR    m_szName[MAX_NAME_LEN];
    
int        m_iAge;
private:
}
;

class CClass
{
public:
    CStudent
* FindStudentByName(LPCTSTR lpszName);
    
void    PushStudent(CStudent& student);
protected:
    list
<CStudent> m_lstStudent;
    TCHAR    m_szName[MAX_NAME_LEN];
private:
}
;

student.cpp

CStudent* CClass::FindStudentByName(LPCTSTR lpszName) const
{
    list
<CStudent>::iterator it;
    
for (it=m_lstStudent.begin(); it!=m_lstStudent.end(); it++)
    
{
        
if (_tcsicmp(it->m_szName, lpszName) == 0)
        
{
            
return (CStudent*)it;
        }

    }

    
return NULL;
}


void CClass::PushStudent(CStudent& student)
{
    m_lstStudent.push_back(student);
}

main.cpp
int main()
{
    CClass ccl;
    ZeroMemory(
&ccl, sizeof(CClass));
    CStudent cst;
    cst.SetAge(
18);
    cst.SetName(_T(
"Yisong"));

    ccl.PushStudent(cst);
    
return 0;
}

CClass类中定义了list成员变量m_lstStudent;
在使用CClass时对其进行了清零操作
ZeroMemory(&ccl, sizeof(CClass));
这样把链表申请到的内存指针_Head置为NULL,导致在使用该链表时产生访问违规。
原创粉丝点击