您的位置:首页 > 其它

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

2012-08-10 10:18 274 查看
有一个类

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不会指向真正的字符串。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: