内存泄露:
- 第一次new的int就会发生内存泄露。(无用,但是占据内存)
#include <iostream>
using namespace std;
int main()
{
int *pTemp = new int();
cout << pTemp << endl;
*pTemp = 1;
pTemp = new int();
delete pTemp;
cout << pTemp << endl;
cout << *pTemp << endl;
cout << "执行结束了" << endl;
return 0;
}
迷途指针:
野指针
智能指针:
shared_ptr 共享指针:
- 多个智能指针可以指向相同对象,该对象和其相关资源会在“最后一个引用被销毁”时候释放。
示例代码:
#include <iostream>
#include <memory>
using namespace std;
int main()
{
string *s1 = new string("s1");
shared_ptr<string> ps1(s1);
shared_ptr<string> ps2;
ps2 = ps1;
cout << ps1.use_count() << endl;
cout << ps2.use_count() << endl;
cout << ps1.unique() << endl;
string *s3 = new string("s3");
shared_ptr<string> ps3(s3);
cout << (ps1.get()) << endl;
cout << ps3.get() << endl;
swap(ps1, ps3);
cout << ps1.get() << endl;
cout << ps3.get() << endl;
cout << ps1.use_count() << endl;
cout << ps2.use_count() << endl;
cout << ps2.get() << endl;
ps2 = ps1;
cout << ps2.get() << endl;
cout << ps1.use_count() << endl;
cout << ps2.use_count() << endl;
cout << ps3.use_count() << endl;
ps1.reset();
cout << ps1.use_count() << endl;
cout << ps2.use_count() << endl;
return 1;
}
成员函数:
unique_ptr
#include <iostream>
#include <memory>
using namespace std;
int main()
{
unique_ptr<string> pu1(new string("hello world"));
unique_ptr<string> pu2;
unique_ptr<string> pu3;
pu3 = unique_ptr<string>(new string("YOU"));
cout << "---------------" << endl;
return 0;
}
weak_ptr
- weak_ptr是用来解决shared_ptr相互引用时的死锁问题,
- 如果说两个shared_ptr相互引用,那么这两个指针的引用计数永远不可能下降为0,资源永远不会释放。
- 它是对对象的一种弱引用,不会增加对象的引用计数,
- 和shared_ptr之间可以相互转化,shared_ptr可以直接赋值给它,它可以通过调用lock函数来获得shared_ptr。
访问: