C++11 shared_ptr 智能指针 的使用,避免内存泄露

2023-01-04,,,,

多线程程序经常会遇到在某个线程A创建了一个对象,这个对象需要在线程B使用,

在没有shared_ptr时,因为线程A,B结束时间不确定,即在A或B线程先释放这个对象都有可能造成另一个线程崩溃,

所以为了省时间一般都是任由这个内存泄漏发生.

当然也可以经过复杂的设计,由一个监控线程来统一删除,

但这样会增加代码量和复杂度.这下好了,shared_ptr 可以方便的解决问题,因为它是引用计数和线程安全的.

shared_ptr不用手动去释放资源,它会智能地在合适的时候去自动释放。

我们来测试看看效果

 //C++11 shared_ptr 智能指针 的使用,避免内存泄露
#include <iostream>
#include <memory>
using namespace std; #define _PRT(T) std::shared_ptr<T> //定义 shared_ptr<T> 的智能指针
#define _PRTO(T,N,...) std::shared_ptr<T> N(new T(##__VA_ARGS__)) //定义 shared_ptr<T> 的数组智能指针
#define _PRTA(T,N,n) std::shared_ptr<T> N(new T[n]) class A {
public:
int n;
A(int n):n(n) {
cout <<n<< " construct A!!!" << endl;
}
;
~A() {
cout <<n<< " destruct A!!!" << endl;
}
;
void Out(){ cout << n * << endl; }
};
class B : public A {
public:
B(int n):A(n) {
cout <<n<< " construct B!!!" << endl;
}
;
~B() {
cout <<n<< " destruct B!!!" << endl;
}
;
_PRT(A) geta(int n) { _PRTO(A,a,n); return a; } void chars() {
//使用智能指针指向 char[],以自动释放
_PRTA(char,p,*);
strcpy(p.get(), "std::shared_ptr<char*>");
printf(p.get());
} };
int main() {
B* ptrB0 = new B();
ptrB0->Out(); _PRT(B) ptrB1(new B());
ptrB1->Out();
_PRT(A) a = ptrB1->geta();
a->Out();
//复制了指针,增加引用计数
_PRT(B) ptrB2 = ptrB1; _PRT(A) b = ptrB2->geta();
b->Out();
ptrB2->Out(); //使用智能指针,会自动释放
for(int i=;i;i--)
ptrB2->chars();
}

测试程序中循环了100次,每次 new 了1Mb的内存, 调试过程中可以看到每次循环完内存都没有增长;

并且main执行完后,直接new的 类1 没有释放, 而类2自动释放了,

并且 如果有赋值给其他shared_ptr指针, 指针指向的对象不会释放,即指针指向的对象不会失效, 除非所有指向此对象的指针都无效了/不用了, 此对象才会自动释放.

C++11 shared_ptr 智能指针 的使用,避免内存泄露的相关教程结束。

《C++11 shared_ptr 智能指针 的使用,避免内存泄露.doc》

下载本文的Word格式文档,以方便收藏与打印。