您的位置:首页 > 编程语言 > C语言/C++

关于C++中const & 返回类型的一些看法

2009-11-26 14:58 573 查看
看下面这段代码

class CPEntry{

public:

    char *m_pName;

    ~CPEntry()

    {

        if (NULL != m_pName)

        {

            delete m_pName;

        }

    }

};

class A

{

public:

    CPEntry m_Entry;

   

    const CPEntry & GetObject()

    {

        return m_Entry;

    }

};

int main()

{

    A test;

    test.m_Entry.m_pName = new char[20];

    sprintf(test.m_Entry.m_pName, "%s", "this is ok");

    printf("%s", test.m_Entry.m_pName );

   

    CPEntry temp = test.GetObject();

       

    printf("%s", test.m_Entry.m_pName );

    return 0;

}

上面的这段代码在编译时没有任何的警告,运行时也不会出现问题。但当CPEntry有一个指针类型的变量时就可能会引发无效指针问题。
再看下面这段代码: class CPEntry{

public:

    char *m_pName;

    ~CPEntry()

    {

        if (NULL != m_pName)

        {

            delete m_pName;

        }

    }

};

class A

{

public:

    CPEntry m_Entry;

   

    const CPEntry & GetObject()

    {

        return m_Entry;

    }

};

int main()

{

    A test;

    test.m_Entry.m_pName = new char[20];

    sprintf(test.m_Entry.m_pName, "%s", "this is ok");

    printf("%s", test.m_Entry.m_pName );

    {

        CPEntry temp = test.GetObject();

    }

   

    printf("%s", test.m_Entry.m_pName );

    return 0;

}

注意看printf("%s", test.m_Entry.m_pName ); {
CPEntry temp = test.GetObject();
}这段代码,temp出了作用域被释放,CPEntry的指针被删除,所以再次使用会发生崩溃。这是在实际工作中遇到的一个问题,用了几个小时去调这个BUG。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ class delete null 工作