c++智能指针自定义删除器和封装成C接口举例

本文介绍了在C++开发中如何使用智能指针(如unique_ptr)来有效管理对象,避免内存泄漏。通过示例解释了自定义删除器的必要性,并提醒开发者注意智能指针在特定情况下的使用细节,如防止野指针和二次释放问题。同时,讨论了make_unique和make_shared的差异,以及何时需要自定义 deleter。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在开发过程中,我们可能会经常使用第三方的库和接口来不断地New对象,这时我们要考虑,使用智能指针来管理我们的对象,不然函数中有大量的Return或者函数结束,就需要我们去释放分配的对象,维护起来也比较麻烦,也可能造成内存的泄露。因此要巧妙的使用智能指针来提高开发效率,下面给出演示例子:

#include<iostream>
#include<memory>
using namespace std;


class MyString
{
public:
	MyString(char*str=NULL) 
	{
		if (str == NULL)
		{
			m_pStr = new char(1);
			*m_pStr = '\0';
			//m_pStr = new char(3);
			//strcpy(m_pStr, "12");
		}
		else
		{
			size_t length_of_string = strlen(str);
			m_pStr = new char(length_of_string + 1);
			strcpy(m_pStr, str);
		}
	}
	inline MyString& operator =(const MyString&other)
	{
		if (this == &other)
		{
			return *this;
		}
		//释放原有的内存资源
		delete[] m_pStr;
		// 分配新的内存资源
		size_t length = strlen(other.m_pStr);
		m_pStr = new char(length + 1);
		strcpy(m_pStr, other.m_pStr);
	}

	MyString(const MyString&other)
	{
		int length = strlen(other.m_pStr);
		m_pStr = new char(length + 1);
		strcpy(m_pStr, other.m_pStr);

	}

	~MyString() 
	{
		cout << "this is defalut deconstrucion is MyString" << endl;
		if (m_pStr)
		{
			delete[] m_pStr;
			m_pStr = NULL;
		}
	}

	char* GetStr() {
		return m_pStr;
	}

private:
	char*m_pStr;
};


struct DeleterMyString
{
	inline void operator() (MyString*pMyRect)
	{
		cout << "this is new deconstruction in DeleterMyString" << endl;
		if (pMyRect)
		{
			delete[] pMyRect->GetStr();
		}
	}
};

typedef struct _t_FPD_MyString* FPD_MyString;

FPD_MyString FPD_MyStringNew(char*pStr) {
	return (FPD_MyString)new MyString(pStr
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值