c++11 智能指针 之 shared_ptr

使用:

// 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;
}

输出:

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

 

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恋恋西风

up up up

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值