指针的危害
- 指针未初始化
- 野指针
- 内存泄漏
0.智能指针分类

- 本质:
将指针封装为类对象成员,并在析构函数里删除指针指向的内存。 - 不同:
auto_ptr、unique_ptr、scoped_ptr马上删除。
shared_ptr计数为0删除。
weak_ptr不删除。
智能指针是来解决指针危害的。
1. auto_ptr
- 作用
对作用域内的动态分配对象的自动释放 - 基本类型
#include <iostream>
#include <memory>
using namespace std;
int main(){
int* pn = new int(10);
auto_ptr<int> ap(pn);
cout << *ap << endl;
}
- 类类型
#include <iostream>
#include <memory>
using namespace std;
class Test{
public:
Test(){
cout << __func__ << endl;}
~Test(){
cout << __func__ << endl;}
void Func(){
cout << __func__ << endl;}
};
int main(){
Test* pt = new Test;
auto_ptr<Test> apt(pt);
apt->Func();
}
通过valgrind可以看到没有内存泄露,指针可以被正常释放。
- 缺陷
- 两个
auto_ptr不能同时拥有同一个对象
#include <memory>
using namespace std;
int main(){
int* pn = new int(10);
auto_ptr<int> ap1(pn);
auto_ptr<int> ap2(pn);
}
auto_ptr不能管理数组指针
#include <memory>
using namespace std;
int main(){
int*pa=new int[10];
auto_ptr<int>ap(pa);
}
auto_ptr被拷贝或被赋值后,失去对原指针的管理.这种情况被称为指针所有权传递。
- 赋值的情况
#include <iostream>
#include <memory>
using namespace std;
int main(){
int*p = new int(10);
auto_ptr<int> ap1(p);
cout<< *ap1 <<endl;
auto_ptr<int> ap2=ap1;
cout
本文介绍了C++中的智能指针,包括其分类和作用,如解决野指针、内存泄漏问题。重点讲解了、的区别,以及在解决循环引用问题上的策略。并提到了使用智能指针的一些最佳实践,如Effective C++和Effective Modern C++中的相关条款,强调了智能指针在防止内存泄漏中的重要性。
最低0.47元/天 解锁文章
885

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



