今天看C++primer看到智能指针这一块,结合网络视频大概了解了一些,写一段代码帮助自己理解智能指针的实现方式,智能指针根据自己初步理解,是一个“带指针的类”:
1.这是一个给类‘Septe’的智能指针。
2.创造额外内存空间进行深拷贝。
3.智能指针在栈中析构时调用析构函数,清理堆上的内容。
4.重载运算符‘->’让它像一个指针,注意此处返回一个const变量所以‘Septe’类中的函数要接受const否则会qulifier缺少调用参数资格。
5.销毁‘Septe’的智能指针并没有影响拷贝,因为是深拷贝。address1和address2是Septe里a2_这个变量的地址。
#include <iostream>
using namespace std;
class Septe
{
private:
int a1_;
public:
int a2_ = 3;
Septe():
a1_(2)
{
}
Septe(int a1):
a1_(a1)
{
}
public:
void print()const {cout << "congratulation";}
};
class Auptr //1.This is smartpointer for class Septe
{
private:
Septe* ptr_;
public:
Auptr(Septe* p1):
ptr_(p1)
{
}
Auptr(const Auptr& paratype)
{
this->ptr_ = new Septe(paratype.a1_); //2.Creat a new storage space for deepcopy
}
~Auptr()
{
delete ptr_; //3.Clear the storage on the heap
}
public:
const Septe* operator->()const //4.Overload the operator"->" let the class look like a pointer
{ //the function return const parameter so printfunction should recive const
return ptr_;
}
};
int main ()
{
const Auptr theptr = new Septe(9);
const Auptr theptr2 = theptr;
int address1 = (int)&(theptr)->a2_;
int address2 = (int)&(theptr2)->a2_;
theptr->print();
cout << ' '<< address1 << ' ';
theptr.~Auptr(); //5.Destruct the smartpointer theptr and the thetr2 still work cause we deepcopy it.
cout << ' '<< address2 << ' ';
return 0;
}