C++没有模板的智能指针大概是什么样的

今天看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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值