使用:

// new array 
_PRTA(unsigned char, fileBuffer, filesize + 1);

// new point
_PRT(StructA) mStructA;
mStructA = make_shared<StructA>(111);

shared_ptr不用手动去释放资源,它会智能地在合适的时候去自动释放,这个对于C++内存泄漏和编程效率会有很大的提高;

 以前我们常为忘记 delete,并且在多线程释放内存时很纠结 ,shared_ptr 可以方便的解决问题,因为它是引用计数和线程安全的。

写个简单的demo:

#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 SharePtr {
public:
string name;
SharePtr() {
name = "SharePtr";
cout << "\n construct SharePtr" << endl;
}
SharePtr(string name) :name(name) {
cout << "\n construct SharePtr" << endl;
}
;
~SharePtr() {
cout << " \n destruct SharePtr" << endl;
}
;
void printf() { cout << name.c_str() << endl; }
};

shared_ptr<SharePtr> easyPtr(string name)
{
_PRT(SharePtr) ptrS(new SharePtr(name));
ptrS->printf();
return ptrS;
}

void easyPtrArray()
{
//使用智能指针,会自动释放
_PRTA(char, p,1024);
char cstr[] = { "share_ptr test" };
strncpy(p.get(), cstr,strlen(cstr));
}

void nativePtrArray()
{
//使用智能指针,会自动释放
char * p = new char[1024];
char cstr[] = { "share_ptr test" };
strncpy(p , cstr, strlen(cstr));
}
int main() {

//复制了指针, 增加引用计数
_PRT(SharePtr) pShare = easyPtr("easy ptr");

cout << pShare.get()->name.c_str() << endl;

//使用智能指针,会自动释放
for (int i = 5; i; i--)
easyPtrArray();
// 运行完内存没有增加 使用vs 诊断工具可以看到
//使用普通指针,不自动释放
for (int i = 5; i; i--)
nativePtrArray();
//运行完内存没有增加 5K 泄漏5K 使用vs 诊断工具可以看到
return 0;
}

输出:

主要太爽的是不用再想着去释放内存。

c++11 智能指针 之 shared_ptr_#include