在开发过程中,我们可能会经常使用第三方的库和接口来不断地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