警惕利用类的构造和析构函数来做资源分配释放时候,对临时变量的使用

有一个类

class CMiRegularPath
{
public:
    CMiRegularPath(LPCTSTR lpPath);
    ~CMiRegularPath();

    operator LPCTSTR ();
    operator LPTSTR();

protected:
    LPTSTR m_lpPathBuffer;
    LPCTSTR m_lpPath;
    LPCTSTR m_lpPathRegular;
};

下面是调用

void func1(LPTSTR lpPointer)
{

}

void func2(LPCTSTR lpPointer)
{

}

void test
{
    func1(CMiRegularPath(_T("D:\\aa/AS")));
    func2(CMiRegularPath(_T("D:\\aa/AS")));
    LPTSTR lpP1 = CMiRegularPath(_T("D:\\aa/AS"));
    LPCTSTR lpP2 = CMiRegularPath(_T("D:\\aa/AS"));
}

真相

test函数中前两个调用是对的,在func1和func2中能得到正确的字符串,后两个是错误的,执行完这一行后马上就会执行类的析构函数,所以lpP1,lpP2不会指向真正的字符串。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章