C++智能指针简单实现
#include <stdio.h> #include <stdlib.h> class Temp { public: Temp() { printf("%s:构造函数\n", __FUNCTION__); } ~Temp() { printf("%s:析构函数\n", __FUNCTION__); } void func() { printf("%s\n", __FUNCTION__); } private: }; template <class T> class SmartPointer { public: SmartPointer(){} SmartPointer(T* data) { p = data; } ~SmartPointer() { delete p; } //重载->运算符 T* operator->() { return p; } T& operator*() { return *p; } private: T* p; };
int main(int argc, char* argv[]) { SmartPointer<Temp> sp(new Temp); //sp.operator->()->func(); sp->func(); (*sp).func(); getchar(); return 0; }
本文来自博客园,作者:一夜梦想,转载请注明原文链接:https://www.cnblogs.com/caiyingyong/p/17158777.html