congfeng02 发表于 2013-2-5 02:43:59

使用C++标准类库的智能指针(源代码)

#include "stdafx.h"#include <iostream>#include <string>#include <cstring>#include <memory>using namespace std;class CMyStr{public:CMyStr(const char* pstr){cout << "CMyStr::CMyStr()" << endl;m_pData = NULL;if (NULL == pstr){cout << "param is null!";return;}int nLen = strlen(pstr) + 1;m_pData = new char;if (NULL == m_pData){cout << "get memory failed..." << endl;return;}strncpy(m_pData, pstr, nLen);}~CMyStr(){cout << "CMyStr::~CMyStr()" << endl;if (NULL != m_pData){delete[] m_pData;m_pData = NULL;}}const char* c_str(){return m_pData;}private:char*m_pData;};int main(){auto_ptr<CMyStr> pStr(new CMyStr("hello, andylin!"));cout << pStr->c_str() << endl;auto_ptr<string> pstr2(new string("I love my baby so much!"));cout << pstr2->c_str() << endl;return 0;}
页: [1]
查看完整版本: 使用C++标准类库的智能指针(源代码)