用类模板实现C++智能指针

首先是一段错误的代码

#include<iostream>

using namespace std;

template<class T>
class autoPtr {
public:
	//构造函数,创建一个T类型的指针并赋值n
	autoPtr(T n)
	{
		T *ptr = new T;
		*ptr = n;
		cout << "new pointer created." << endl;
		cout << *ptr << endl; //这个地方可以输出ptr指向的值
	}
	//构造函数
	autoPtr() {};
	//析构函数
	~autoPtr()
	{
		delete ptr;
		cout << "pointer destroyed." << endl;
	}
	//用这个函数来输出ptr指向的值
	void show()
	{
		cout << *ptr << endl;//这个地方不能输出,内存无法读取
		cout << "That is the value of ptr." << endl;
	}
private:
	T* ptr;
};

int main()
{
	autoPtr<int> pt(5);
	pt.show();

	return 0;
}

VS2017报错

ptr为什么是个nullptr呢,明明在构造函数中都给ptr赋值了。

看了好久,才发现tmd是namespace出了问题,在构造函数中new出来了一个ptr,覆盖了类中private的ptr。

这个时候把构造函数稍作修改,

//构造函数,创建一个T类型的指针并赋值n
	autoPtr(T n)
	{
		ptr = new T;//去掉T*,直接用Private里T*好的ptr
		*ptr = n;
		cout << "new pointer created." << endl;
		cout << *ptr << endl; //这个地方可以输出ptr指向的值
	}

这个时候,程序就能愉快的运行啦! 

猜你喜欢

转载自blog.csdn.net/o707191418/article/details/85682676