自制shared pointer遇阻:无法让构造函数接收任意类型指针
解决自定义智能指针支持任意类型的问题
嘿,我完全懂你现在卡在这儿的感觉——想自己实现一个能指向任意类型的智能指针,结果现在只能绑定特定的P类对吧?其实解决这个问题的核心就是用C++模板来实现泛型设计,让你的SmartP类能适配任意数据类型。
问题根源
你当前的SmartP类把成员指针ptr直接定义成了P*,构造函数也只接受P*类型的参数,这就导致它只能处理P类的对象,没法兼容P2或者其他类型。
改造方案:把SmartP改成模板类
我们只需要把SmartP定义为模板类,用一个类型参数T来替代原来硬编码的P,这样它就能接受任意类型的指针了。下面是改造后的完整代码:
#include <iostream> #include <memory> class P //dummy class { int x; public: P() : x(42) {} ~P() {} void print() { std::cout<<"Address = "<< this << "\n"; } }; class P2 //dummy class 2 { public: P2() {} ~P2() {} void print() { std::cout<<"Address = "<< this << "\n"; } }; // 修改为模板类,支持任意类型T template<typename T> class SmartP { T *ptr; public: // 构造函数接受任意类型T的指针 SmartP(T *p) : ptr(p) {} // 析构函数自动释放T类型的对象 ~SmartP() { delete ptr; } // 重载*运算符,返回T类型的引用 T& operator* () { return *ptr; } // 重载->运算符,返回T类型的指针 T* operator-> () { return ptr; } }; void rawPointer() { P *p(new P); p->print(); delete p; //when removed, next allocated address will be different } void smartPointerOwn() { SmartP<P> spo(new P); // 指定模板参数为P spo->print(); // 现在这行代码可以正常工作啦! SmartP<P2> spo2(new P2); spo2->print(); } void smartPointer() { std::unique_ptr<P> sp(new P); sp->print(); //Do not need a delete } int main() { rawPointer(); smartPointerOwn(); smartPointer(); std::cin.get(); //Prevent exiting console prematurely return 0; }
关键改动说明
- 用
template<typename T>声明模板类,T是我们的类型占位符,可以代表任意类型(比如P、P2、int等等) - 把原来的
P* ptr改成T* ptr,让成员指针能指向任意类型的对象 - 构造函数、析构函数以及运算符重载都用
T替换原来的P,确保所有操作都适配当前的类型参数 - 使用的时候,需要通过
SmartP<类型>的方式指定具体的类型(比如SmartP<P>或者SmartP<P2>)
这样改造之后,你的自定义智能指针就和标准库的std::unique_ptr一样,能处理任意类型的指针啦!
内容的提问来源于stack exchange,提问作者MemoryLeak42
相关产品推荐
相关产品推荐

