Memory leak: dynamically apply for heap space, and do not return it after use. There is no garbage collection mechanism in C++, and the pointer cannot control the life cycle of the pointed heap space.
#include <iostream>
#include <string>
using namespace std;
class Test
{
int i;
public:
Test(int i)
{
this->i = i;
}
int value()
{
return i;
}
~Test()
{
}
};
int main()
{
for(int i=0; i<5; i++)
{
Test* p = new Test(i); //没有归还空间
cout << p->value() << endl;
}
return 0;
}
A special pointer is required, and the heap space is actively released at the end of the life cycle,
A piece of heap space can only be identified by at most one pointer (only copy constructors and overloaded assignment operators are required)
Avoid pointer arithmetic and pointer comparisons.
Solution:
Overloading pointer trait operators (-> and *)
It can only be overloaded through the member function of the class, the overloaded function cannot use parameters, and only one overloaded function can be defined.
#include <iostream>
#include <string>
using namespace std;
class Test
{
int i;
public:
Test(int i)
{
cout << "Test(int i)" << endl;
this->i = i;
}
int value()
{
return i;
}
~Test()
{
cout << "~Test()" << endl;
}
};
//智能指针
class Pointer
{
Test* mp;
public:
Pointer( Test* p = NULL )
{
mp = p;
}
Pointer(const Pointer& obj)
{
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL; //去掉只读属性
}
Pointer& operator = (const Pointer& obj)
{
if( this != &obj )
{
delete mp;
mp = obj.mp;
const_cast<Pointer&>(obj).mp = NULL;
}
return *this;
}
Test* operator -> ()
{
return mp;
}
Test& operator * ()
{
return *mp;
}
bool isNull()
{
return (mp == NULL);
}
~Pointer()
{
delete mp;
}
};
int main()
{
Pointer p1 = new Test(0); //用pointer类对象代替指针
cout << p1->value() << endl;
Pointer p2 = p1;
cout << p1.isNull() << endl;
cout << p2->value() << endl;
return 0;
}
Smart pointers: simulate the behavior of pointers by replacing pointers with an object.
Military rules for the use of smart pointers: can only be used to point to objects or variables in the heap space,
Pointer feature operators (-> and *) can be overloaded. Overloaded pointer feature operators can use objects instead of pointers to avoid memory problems to the greatest extent.