sheared_ptr
#include <string>
#include <iostream>
using namespace std;
template <typename T>
class Sharedptr {
public:
Sharedptr():count(new size_t), ptr(nullptr){}
Sharedptr(T* p) : count(new size_t(1)), ptr(p){}
Sharedptr(const Sharedptr<T>& other) : count(other.count), ptr(other.ptr){
if (nullptr != ptr) {
++(*count);
}
}
Sharedptr(const Sharedptr<T>&& other) : count(other.count), ptr(other.ptr) {
++(*count);
}
T* operator->() { return ptr; }
T& operator*() { return *ptr; }
operator bool() { return ptr == nullptr; }
Sharedptr<T>& operator=(const Sharedptr<T>& other) {
if (this == &other) return *this;
++ *other.count;
if (this->ptr && 0 == -- *this->count) {
delete count;
delete ptr;
count = nullptr;
ptr = nullptr;
cout << "delete ptr =" << endl;
}
this->ptr = other.ptr;
this->count = other.count;
return *this;
}
T* get() { return ptr; }
size_t use_count() { return *count; }
bool unique() { return *count == 1; }
~Sharedptr() {
if (ptr && -- * count == 0) {
delete count;
delete ptr;
ptr = nullptr;
count = nullptr;
cout << "delete ptr ~" << endl;
}
}
private:
size_t* count;
T* ptr;
};
int main(int argc, const char* argv[]) {
Sharedptr<string> pstr(new string("abc"));
cout << "pstr:" << pstr.use_count() << " " << *pstr << endl;
if (pstr) {
cout << "pstr is not nullptr." << endl;
}
Sharedptr<string> pstr2(pstr);
cout << "pstr:" << pstr.use_count() << " " << *pstr << endl;
cout << "pstr2:" << pstr2.use_count() << " " << *pstr2 << endl;
Sharedptr<string> pstr3(new string("hao"));
cout << "pstr3:" << pstr3.use_count() << " " << *pstr3 << endl;
pstr3 = pstr2;
cout << "pstr:" << pstr.use_count() << " " << * pstr << endl;
cout << "pstr2:" << pstr2.use_count() << " " << *pstr2 << endl;
cout << "pstr3:" << pstr3.use_count() << " " << *pstr3 << endl;
auto pstr4 = pstr3.get();
cout << "pstr3:" << pstr3.use_count() << " " << *pstr4 << endl;
cout << "pstr3->size(): " << pstr3->size() << endl;
cout << "pstr3.size(): " << (*pstr3).size() << endl;
return 0;
}