I'm having trouble storing instances of my smart pointer into a container. Here is the code for the pointer.
#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) {} // default constructor
explicit counted_ptr(const counted_ptr& p) : pointer(p.pointer), count(p.count) { ++*count; } // copy constructor
~counted_ptr()
{
--*count;
if(!*count) {
delete pointer;
delete count;
}
}
counted_ptr& operator=(const counted_ptr& p) // copy assignment
{
pointer = p.pointer;
count = p.count;
++*count;
return *this;
}
T* operator->() const{ return pointer; }
T& operator*() const { return *pointer; }
int& operator[](int index) { return pointer[index]; }
int Get_count() const { return *count; } // public accessor for count
};
int main()
{
counted_ptr<double>one;
counted_ptr<double>two(one);
one = new double(5);
vector<counted_ptr<double> >test;
}
In int main(), the vector<counted_ptr<double> >
line does compile. When I first tried it with just vector<counted_ptr<double> >
it didn't compile (probably because it was lacking parameters.) However, when I try to use push_back such as
test.push_back(one);
I get a compiler error that opens up vector.tcc with the specific error saying that
no matching function for call to `counted_ptr<double>::counted_ptr(const counted_ptr<double>&)'|
I'm guessing that push_back can't find a counted_ptr, but I'm really not sure. Any help is appreciated, thanks.
Edit: However, this works. test[0] = one; I guess the semantics of push_back are what is restricting it.