您的位置:首页 > 编程语言 > C语言/C++

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

2009-06-29 10:57 441 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: