代码拉取完成,页面将自动刷新
//智能指针的理解和使用
#include <iostream>
using namespace std;
// ***************** 为什么要有智能指针呢 ?
#if 0
struct Ptr
{
Ptr() {}
~Ptr() { delete _ptr; _ptr = nullptr; cout << "~Ptr()" << endl; }
int* _ptr = nullptr;
};
#endif
////演示代码
//double Division(const int a , const int b)
//{
//
// Ptr* ptr1 = new Ptr();
// Ptr* ptr2 = new Ptr();
//
// // a / b
// if (b == 0)
// throw(string("Division Zero Error !"));
//
// //调用 Ptr 的析构函数
// delete ptr1;
// delete ptr2;
//
// return (double)a / b;
//
//}
// ***************** 为什么智能指针可以有效避免资源泄漏呢 ?
//演示代码
template <class T>
class smart_ptr
{
public:
//RAII 思想
smart_ptr(T* ptr)
:_ptr(ptr)
{}
~smart_ptr()
{
delete _ptr;
_ptr = nullptr;
cout << "~smart_ptr()" << endl;
};
//还要像普通指针一样 , 重载 * ->
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
private:
T* _ptr;
};
//演示代码
double Division(const int a, const int b)
{
//这里 new 的底层是 operator new , 底层是 malloc , 返回是还是指针
//所以可以用智能指针接受
smart_ptr<int> ptr1(new int(1));
smart_ptr<int> ptr2(new int(2));
// a / b
if (b == 0)
throw(string("Division Zero Error !"));
return (double)a / b;
}
//int main()
//{
// int a = 0, b = 0;
// cin >> a >> b;
//
// try
// {
// cout << Division(a, b) << endl;;
// }
// catch (const string& str)
// {
// cout << str << endl;
// }
// catch (...)
// {
// cout << "Unknown Exception !" << endl;
// }
// return 0;
//}
// ***************** 智能指针的使用
//因为智能指针是解决资源泄漏,也就是自定义类型
#include <memory>
struct Ptr
{
//强制默认构造
Ptr() = default;
Ptr(int* ptr)
:_ptr(ptr)
{}
~Ptr()
{
delete _ptr;
_ptr = nullptr;
cout << "~Ptr()" << endl;
}
int* _ptr = nullptr;
};
// unique_ptr 和 auto_ptr 使用
void Test01()
{
//不支持这样写 , 因为增加了 explicit 修饰 , 即不支持隐式类型转换
//auto_ptr<Ptr> ptr = new Ptr(); // err
int* ptr = new int(1);
auto_ptr<Ptr> ptr1(new Ptr(ptr)); // ok 构造
auto_ptr<Ptr> ptr2(ptr1); // ok 拷贝构造
//这里可以通过调试看到 ptr1 被悬空了 , 很危险 !!!!
//增加了 explicit 修饰, 即不支持隐式类型转换
//unique_ptr<Ptr> ptr3 = new Ptr(); // err
//ptr3 和 arr 是同一块资源
unique_ptr<Ptr> ptr3(new Ptr(ptr)); // ok
//不支持拷贝
//unique_ptr<Ptr> ptr4(ptr3); // err
}
//shared_ptr 使用
void Test02()
{
//template <class U> explicit shared_ptr (U* p);
//不支持隐式类型转换
//shared_ptr<Ptr> ptr1 = new Ptr(); // err
//RAII
int* ptr = new int(1);
shared_ptr<Ptr> ptr1(new Ptr(ptr)); // ok
//支持拷贝
shared_ptr<Ptr> ptr2(ptr1); // ok
//调试可看出 , ptr / ptr1 / ptr2 都指向的同一块资源 , 并且只析构了一次
}
int main()
{
//unique_ptr 和 auto_ptr 使用
//Test01();
//shared_ptr 使用
Test02();
return 0;
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。