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

来源:互联网 发布:室外地垫 知乎 编辑:程序博客网 时间:2024/05/29 14:37

有一个类

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不会指向真正的字符串。