为什么要引入智能指针的概念
我们来看一个例子
void remodel(std::string & str)
{
std::string * ps = new std::string(str);
...
if (weird_thing())
throw exception();
str = *ps;
delete ps;
return;
}
这个函数乍一看好像没问题,但是当出现异常时进入throw exception()
分支,delete将不会被执行,因此就造成了内存泄漏。
避免这种问题的方法:
- 直接在
throw exception();
之前加上delete ps;
(适用于代码规模较小,逻辑较为清晰的的情况下) - 设计一种随着指针生命周期结束自动释放指针指向内存的功能。
类似的问题还有
int main()
{
int *ptr = new int(0); //假设内存申请不成功对异常的处理
delete ptr; //释放后得指针会变成空悬指针野指针
return 0;
}
这时就引入了智能指针,智能指针主要解决了以下问题:
- 处理资源泄露的问题
- 处理空闲指针的问题
为什么C++11要舍弃auto_ptr
C++11从boost库中引入了unique_ptr, shared_ptr, weak_ptr,
同时舍弃了C89的auto_ptr
《C++标准程序库》描述:“auto_ptr
是一种智能指针,帮助程序员防止’被异常抛出时发生资源泄露’”。
但是auto_ptr
有着严格的使用限制
auto_ptr
之间不能共享拥有权auto_ptr
对象通过赋值或构造转移拥有权,一旦拥有权转移,此auto_ptr
所拥有的将是一个原始指针auto_ptr
不适用于array
auto_ptr
不满足STL对容器元素的要求,因此不适用于STL容器。因为在拷贝和赋值之后,新的auto_ptr
和旧的auto_ptr
对象并不相等。- 如果要阻止拥有权的转移,则应该在停止转移之前,将
auto_ptr
声明为const
- 不要使用
auto_ptr
的引用作为实参:因为你不知道拥有权到底有没有转移。如果你不需要转移拥有权,请使用const auto_ptr<class> &
来看以下的几个例子
auto_ptr
的初始化
std::auto_ptr<ClassA> ptr1(new ClassA);//OK
std::auto_ptr<ClassA> ptr2 = new ClassA;//ERROR
auto_ptr
拥有权转移
//initialize an auto_ptr with a new obj
std::auto_ptr<ClassA> ptr1(new ClassA);
//copy the auto_ptr-->transfers the ownership from ptr1 to ptr2
std::auto_ptr<ClassA> ptr2(ptr1); //ptr1拥有权转移,以后不可再对ptr1使用operator*以及operator->
//like copy
std::auto_ptr<ClassA> ptr3 = ptr2; //ptr2拥有权转移给ptr3,以后不可再对ptr2使用operator*以及operator->
std::auto_ptr<ClassA> ptr4(new ClassA); //create a new auto_ptr::ptr4
ptr3 = ptr4; //here ptr3 delete the obj it own ,and then ptr4 transfers the ownership to ptr3。ptr4 own a nullptr
https://www.cnblogs.com/xiehongfeng100/p/4645555.html
http://www.cnblogs.com/lanxuezaipiao/p/4132096.html