I am attempting to understand the internals of std::shared_ptr by writing my own (VERY BASIC) implementation. What I have so far is the following (with most of the operators and other code removed).
template <typename T>
struct ControlBlock {
unsigned int refCount;
T* ptr;
};
template <typename T>
class MyPointer {
//...
private:
ControlBlock<T>* _cb;
};
Everything has been working fine so far except when I try to do the following:
MyPointer<Foo> ptr1;
MyPointer<const Foo> ptr2 = ptr1;
In this case, the non-const pointer cannot be converted to the const pointer because they are two completely different types as far as the template expansion is concerned.
How do I write the pointer in such a way that it allows this (implicit) conversion?
EDIT
I know know from the comments that the pointer should be better implemented as:
struct ControlBlock {
unsigned int refCount;
};
template <typename T>
class MyPointer {
private:
T* _ptr;
ControlBlock* _ctrl;
};
Ultimately, I would like to use this with my own memory pool which will allocate the following:
template <typename T>
struct ControlBlockWrapper {
ControlBlock ctrl;
T value;
};
If my control block contains a pointer back to my pool, I am very confused how I can get from from T* and ControlBlock* (stored by the pointer) to a pointer to the real ControlBlockWrapper that will need to be deleted from the pool. For example, since my pool is creating ControlBlockWrapper's, it's delete method would look something like:
template <typename T>
class Pool {
//...
void destory(ControlBlockWrapper<T>* ptr);
};
Pointer arithmetic seems like a poor way to accomplish this, but I'm not sure how else to do it.