Hi all,
I'm working around with smart pointers mostly as a learning exercise:
I have a single-rooted hierarchy with the root class Object. Every
Object has a member field count, the number of references to the
Object, and a few methods for dealing with reference counts: getCount,
incCount, decCount with the obvious meanings.
To handle these guys I have made a smart pointer template in the usual
way
template<typename T>
class Ref {
private:
T* ptr;
public:
//Descriptors.
T* getPtr() const {
return this->ptr;
};
<etc...>
};
The thingy compiled OK, I wrote a bunch of tests and things were going
OK.
Now, since my hierarchy is single-rooted I thought, hmmm, maybe I
could add up some functionality at Ref<Object> so I started by writing
a full specialization
template<>
class Ref<Object> {
<etc...>
};
And here I had my first surprise: I add to rewrite every single method
for the full specialization even if in most cases it was nothing more
than picking in the Ref<T> general code and replacing T by Object. So
here goes my first question:
Is there any reason why the compiler just doesn't do the obvious
thing? e.g. if a method is not reimplemented in the full
specialization just use the template code replacing the type
parameters?
But my biggest surprise came afterwards. I thought, gee wouldn't be
nice if Derived derived from Object then there is an automatic
conversion Ref<Derived> to Ref<Object>. So in the full specialization
I just changed the copy-constructor from:
Ref(const Ref& ref) : ptr(ref.getPtr()) {
ref->incCount();
};
to
template<typename T>
Ref(const Ref<T>& ref) : ptr(ref.getPtr()) {
ref->incCount();
};
The thing still compiled OK but the first time I ran my tests, a
little dialog box popped up saying that I tried to write to
non-writable memory (this in win2k, the compiler is the one from the
free VC++ toolkit).
Anyone has an inkling of what might be going wrong?
TIA, with my best regards,
G. Rodrigues