Junior — Senior
SharedPtr: implementation of the destructor method
livecode
Task condition
It is necessary to complete the destructor of the simple smart pointer SharedPtr. It should:
- Decrease the ownership counter of the object;
- When it reaches zero, release the managed resource and the counter itself.
template <class T>
class SharedPtr {
int* refCount = nullptr;
T* resource = nullptr;
public:
SharedPtr() = default;
SharedPtr(const SharedPtr& other) {
resource = other.resource;
refCount = other.refCount;
(*refCount)++;
}
explicit SharedPtr(T* p) {
refCount = new int(1);
resource = p;
}
~SharedPtr() {
if (refCount && --(*refCount) == 0) {
delete resource;
delete refCount;
}
}
};