#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[nLen]; 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; }
使用C++标准类库的智能指针(源代码)

最新推荐文章于 2024-09-15 09:39:01 发布