我正在尝试编写自己的共享指针实现(为了好玩/挑战(,但是在无法使构造函数接受任何(自动(类型的指针变量后,我陷入了死胡同。问题是,目前我只能使自己的智能指针指向某个数据类型(类 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";
}
};
class SmartP
{
P *ptr;
public:
SmartP(P *p) : ptr(p) {}
~SmartP()
{
delete ptr;
}
P& operator* ()
{
return *ptr;
}
P* operator-> ()
{
return ptr;
}
};
void rawPointer()
{
P *p(new P);
p->print();
delete p; //when removed, next allocated address will be different
}
void smartPointerOwn()
{
SmartP spo(SmartP(new P));
//This should also work but currently it does not: SmartP spo(SmartP(new P2));
spo->print();
//Do not need a delete
}
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;
}
谢谢!
这里有一些基本的例子来帮助你开始。就像评论中已经提到的,您应该首先检查一些现有的智能指针实现。这个例子非常不完整 - 例如,缺少引用计数(如果需要共享指针(。但它给了你一个想法。我希望它有所帮助。
#include <iostream>
using namespace std;
template <typename T>
class SmartP {
public:
SmartP() : p{nullptr} {}
SmartP(T* pp) : p{pp} {}
~SmartP() { delete p; }
// dereferencing operators
friend T& operator*(const SmartP<T>& sp) { return *(sp.p); }
T& operator->() const { return *p; }
// get the raw pointer
T* get() const { return p; }
private:
T* p;
};
int main() {
SmartP<int> p{new int{3}};
cout << *p << endl;
*p = 4;
cout << *p << endl;
}