I am in writing a smart pointer countedptr and I came across speed. The main function of countedptr is to work like any other smart pointer, and also count how many pointers point to a single object. So far, the code is:
[SOLVED]
#include "std_lib_facilities.h"
template <class T>
class counted_ptr{
private:
T* pointer;
int* count;
public:
counted_ptr(T* p = 0, int* c = new int(1)) : pointer(p), count(c) {}
explicit counted_ptr(const counted_ptr& p) : pointer(p.pointer), count(p.count) { ++*count; }
~counted_ptr() { --*count; delete pointer; }
counted_ptr& operator=(const counted_ptr& p)
{
pointer = p.pointer;
count = p.count;
++*count;
return *this;
}
T* operator->() const{ return pointer; }
T& operator*() const { return *pointer; }
int Get_count() const { return *count; }
};
int main()
{
counted_ptr<double> one;
counted_ptr<double>two(one);
int a = one.Get_count();
cout << a << endl;
}
When I try to do something like
one->pointer = new double(5);
then I get a compiler error saying "query for the" pointer "element in" * (& one) → counted_ptr :: operator-> with T = double ", which has a non-class type double".
I was thinking of creating a function for this, and although I could make a T array allocation function, I can't think of a way to do this to select real objects. Any help is appreciated, thanks.