智能指针的自我/自己的实现
Self/own implementation of smart pointers
我正在尝试编写自己的共享指针实现(为了好玩/挑战(,但是在无法使构造函数接受任何(自动(类型的指针变量后,我陷入了死胡同。问题是,目前我只能使自己的智能指针指向某个数据类型(类 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;
}
相关文章:
- 如何使用ZeroMQ为协议缓冲区编写自己的RPC实现
- 在我自己的堆栈中实现top的问题
- 如何实现自己的生成器以与 std 发行版一起使用
- Qt - 重新实现QIODevice,实时听到我自己的声音
- 自己的C++列表类实现(插入函数)出现问题
- 如何自己为我自己的shared_ptr实现实现别名构造函数
- 如果不在派生类实现中执行此操作,"basic_streambuf"是否会创建自己的获取/放置区域?
- 如何将自己的链表实现从存储整数更改为存储个人数据
- 在 gcc 上自己的元组实现段错误,同时在 clang 中工作
- 智能指针的自我/自己的实现
- 在 C++ 中实现自己的字符串类
- count_if使用我自己的类实现第三个参数
- 试图用c++编写我自己的链表实现,在点击列表中的3个元素后编写segfault代码
- 通过我自己的实现从库中覆盖模板方法
- 实现我自己的获取线函数
- 如何在我自己的全系统模拟器上实现 GDB 调试
- 在OpenGL中实现自己的旋转功能
- 在自己的外壳C++中实现历史记录
- Make_shared - 自己的实现
- 库math.h使用fmod和自己的实现