一、智能指针的意义
- 现代C++开发库中最重要的类模板之一
- C++中自动内存管理的主要手段
- 能够在很大程度上避开内存相关的问题
STL中的智能指针auto_ptr
- 生命周期结束时,销毁指向的内存空间
- 不能指向堆数组,只能指向堆对象(变量)
- 一片堆空间只属于一个智能指针对象
- 多个智能指针对象不能指向同一片堆空间
实例分析1:auto_ptr使用初探
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class Test
{
string m_name;
public:
Test(const char* name)
{
cout << "Hello, " << name << "." << endl;
m_name = name;
}
void print()
{
cout << "I'm " << m_name << "." << endl;
}
~Test()
{
cout << "Goodbye, " << m_name << "." << endl;
}
};
int main()
{
auto_ptr<Test> pt(new Test("D.T.Software"));
pt->print();
return 0;
}
Hello, D.T.Software.//构造函数打印
I'm D.T.Software.//成员函数打印
Goodbye, D.T.Software.//析构函数打印
//我们并没有手动去释放,智能指针智能释放。
#include <iostream>
#include <string>
#include <memory>
using namespace std;
class Test
{
string m_name;
public:
Test(const char* name)
{
cout << "Hello, " << name << "." << endl;
m_name = name;
}
void print()
{
cout << "I'm " << m_name << "." << endl;
}
~Test()
{
cout << "Goodbye, " << m_name << "." << endl;
}
};
int main()
{
auto_ptr<Test> pt(new Test("D.T.Software"));
cout << "pt = " << pt.get() << endl;
pt->print();
cout << endl;
auto_ptr<Test> pt1(pt);//pt1指向堆空间中了一个对象pt,
cout << "pt = " << pt.get() << endl;
cout << "pt1 = " << pt1.get() << endl;
pt1->print();//pt1能够输出 I'm D.T.Software.说明 pt1指向pt成功
return 0;
//输出为:
/*
Hello, D.T.Software.
pt = 0x1715b0
I'm D.T.Software.
pt = 0
pt1 = 0x1715b0
I'm D.T.Software.
Goodbye, D.T.Software.
*/
/*分析:
Goodbye, D.T.Software. 为析构函数打印,这是只有一次,说明析构函数只调用一次。
这是因为 一片堆空间只属于一个智能指针对象。最开始的时候pt指向了堆空间对象,当 auto_ptr<Test> pt1(pt)
之后,pt将所有权转交给pt1了,也就是说 auto_ptr<Test> pt1(pt)之后pt指针就为空了。 可以避免重复释放的问题。
*/
}
实例分析:创建智能指针类模板
#ifndef _SMARTPOINTER_H_
#define _SMARTPOINTER_H_
template
< typename T >
class SmartPointer
{
T* mp;
public:
SmartPointer(T* p = NULL)
{
mp = p;
}
SmartPointer(const SmartPointer<T>& obj)
{
mp = obj.mp;
const_cast<SmartPointer<T>&>(obj).mp = NULL;
}
SmartPointer<T>& operator = (const SmartPointer<T>& obj)
{
if( this != &obj )
{
delete mp;
mp = obj.mp;
const_cast<SmartPointer<T>&>(obj).mp = NULL;
}
return *this;
}
T* operator -> ()
{
return mp;
}
T& operator * ()
{
return *mp;
}
bool isNull()
{
return (mp == NULL);
}
T* get()
{
return mp;
}
~SmartPointer()
{
delete mp;
}
};
#endif
#include <iostream>
#include <string>
#include "SmartPointer.h"
using namespace std;
class Test
{
string m_name;
public:
Test(const char* name)
{
cout << "Hello, " << name << "." << endl;
m_name = name;
}
void print()
{
cout << "I'm " << m_name << "." << endl;
}
~Test()
{
cout << "Goodbye, " << m_name << "." << endl;
}
};
int main()
{
SmartPointer<Test> pt(new Test("D.T.Software"));
cout << "pt = " << pt.get() << endl;
pt->print();
cout << endl;
SmartPointer<Test> pt1(pt);
cout << "pt = " << pt.get() << endl;
cout << "pt1 = " << pt1.get() << endl;
pt1->print();
return 0;
}
本文详细探讨了C++中智能指针auto_ptr的功能与使用,包括其如何解决内存管理问题,避免内存泄漏,并通过实例展示了智能指针在所有权转移和生命周期管理上的特性。

被折叠的 条评论
为什么被折叠?



