Item 28 智能指针
在看着条目之前,我能想到的就是资源管理。
能帮助我们自动释放在heap分配的空间,免去内存泄漏之苦。
我主要想记录下auto_ptr。
首先定义类Test:
class Test
{
public:
Test(int initValue):value(initValue) {}
int getValue() const {return value;}
void printValue() const {cout<<value<<endl;}
private:
int value;
};
(1)auto_ptr的构造函数:
The constructor for objects of type auto_ptr.
explicit auto_ptr( Type* _Ptr = 0) throw( );要求显式调用:
auto_ptr<Test> spTest;
以上就是使用其中默认参数的版本。
auto_ptr<Test> spTest(new Test(10));
将智能指针中的dumb pointer指向了一个Test对象。
还存在其他集中形式的构造函数。用法可参考MSDN。
(2)赋值、复制动作。auto_ptr采取的是转移控制权的策略。
int _tmain(int argc, _TCHAR* argv[])
{
auto_ptr<Test> spTest1(new Test(10));
auto_ptr<Test> spTest2=spTest1;
Test* pt1=spTest1.get();
Test* pt2=spTest2.get();
cout<<pt1<<endl;
cout<<pt2<<endl;
return 0;
}
上述代码在执行过后,spTest1中的dumb pointer指向NULL,而spTest2中的指针指向原来的对象。上述过程调用auto_ptr的拷贝构造函数。复制动作也是相同的道理。
(3)析构。
auto_ptr拥有它所指向的对象,故auto_ptr对象在析构的时候,会删除它所指向的对象。
(4)解引操作符。
Type& operator*( ) const throw( );
Type *operator->( ) const throw( );
这使得一个auto_ptr用起来像一个普通的指针。
int _tmain(int argc, _TCHAR* argv[])
{
auto_ptr<Test> spTest1(new Test(10));
spTest1->printValue();
(*spTest1).printValue();
return 0;
}
(5)测试智能指针是否NULL。
auto_ptr并没有提供这样的机制。书上介绍的方法是重载operator !。
bool operator! () const; //只有当auto_ptr中的dunb pointer为NULL时,返回true。
(6)将智能指针转换为dumb pointer。
Type *get( ) const throw( );智能指针的行为想原始指针,我想不出这个get方法会在什么场景下用到。是不是在维护出现auto_ptr之前的代码所需要。
(7)智能指针与继承有关类型转换。
这点在Effective C++模板与泛型那部分有所总结。通过泛化拷贝构造函数来实现的。
(8)与const。这一点使得一个智能指针看起来就不像一个指针那么自如。
给我们提供的只有一种形式:
const auto_ptr<Test> pt(new Test(10)); //pt是一个const对象,指向一个non-const对象。
另外还有两个比较有用的函数:
auto_ptr::release
The member replaces the stored pointer myptr with a null pointer and returns the previously stored pointer.
auto_ptr::reset
The member function evaluates the expression delete myptr, but only if the stored pointer valuemyptr changes as a result of a function call. It then replaces the stored pointer withptr.