"shared ptr"
Материал из SEWiki
#ifndef _SHAREDPTR_H_
#define _SHAREDPTR_H_
#include "GaussNumber.h"
#define NULL 0
class Storage {
private:
GaussNumber *p_obj;
int count;
public:
Storage(GaussNumber *p_obj);
~Storage();
void increaseCount();
void decreaseCount();
GaussNumber *ptr() const;
bool isNull() const;
};
class shared_ptr {
private:
Storage *storage;
public:
shared_ptr();
shared_ptr(GaussNumber *p_obj);
shared_ptr(const shared_ptr &sptr);
~shared_ptr();
const shared_ptr &operator=(const shared_ptr &sptr);
GaussNumber &operator*() const;
GaussNumber *operator->() const;
GaussNumber *ptr() const;
bool isNull() const;
};
#endif
#include "shared_ptr.h"
// Storage class definitions
Storage::Storage(GaussNumber *p_obj) {
this->p_obj = p_obj;
count = 1;
}
Storage::~Storage() {
if (p_obj != NULL)
delete p_obj;
}
void Storage::increaseCount() {
count++;
}
void Storage::decreaseCount() {
count--;
if (count == 0)
delete this;
}
GaussNumber *Storage::ptr() const {
return p_obj;
}
bool Storage::isNull() const {
if (p_obj == NULL)
return true;
else
return false;
}
// shared_ptr class definitions
shared_ptr::shared_ptr() {
storage = new Storage(NULL);
}
shared_ptr::shared_ptr(GaussNumber *p_obj) {
storage = new Storage(p_obj);
}
shared_ptr::shared_ptr(const shared_ptr &sptr) {
storage = sptr.storage;
storage->increaseCount();
}
shared_ptr::~shared_ptr() {
storage->decreaseCount();
}
const shared_ptr &shared_ptr::operator=(const shared_ptr &sptr) {
sptr.storage->increaseCount();
storage->decreaseCount();
storage = sptr.storage;
return *this;
}
GaussNumber &shared_ptr::operator*() const {
return *storage->ptr();
}
GaussNumber *shared_ptr::operator->() const {
return storage->ptr();
}
GaussNumber *shared_ptr::ptr() const {
return storage->ptr();
}
bool shared_ptr::isNull() const {
return storage->isNull();
}