template <typename T>
class shared_ptr {
public:
shared_ptr(): p(nullptr), use(new std::size_t(1)) { }
explicit shared_ptr(T *pt): p(pt), use(new std::size_t(1)) { }
shared_ptr(const shared_ptr &sp): p(sp.p), use(sp.use) { if (use) ++*use; }
shared_ptr& operator=(const shared_ptr&);
~shared_ptr();
T& operator*() { return *p; }
const T& operator*() const { return *p; }
private:
T *p;
std::size_t *use;
};
template <typename T>
shared_ptr<T>::~shared_ptr() {
if (use && 0 == --*use) {
delete p; // del ? del(p) : delete p;
delete use;
}
}
如上所示。是C++ Primer 第五版16.1.6节的一个问题,请问我应该给shared_ptr类增加一个什么类型的成员del,才能够使得这个类可以接受一个可调用对象,此对象的目的是清理动态内存分配的指针,但是可以自定义这个对象的行为。
谢谢!
You can refer to it. . .
You can maintain a function pointer of type void (*)(T*) in shared_ptr, and then call this function when you need to release memory. A simple example:
I am too naive=,-, you can read this answer About the deleter in shared_ptr in c++
Referred to araraloren’s answer, thank you!