Recently I have been really wanting to do SmartPointers in QubLib. This part of QubLib will only be operational in the C++ version of QubLib, because the Java and D versions will already have garbage collection, so they won't need SmartPointers. The way I chose to implement smart pointers is by having a templatized Ptr class that will act like any normal pointer. The only difference is that when this pointer is assigned to point at something, it registers what it is pointing at with a singleton PtrManager class. The pointer manager registers the address that the pointer points to, and then continues to keep track of how many Ptr objects are pointing at that address. When a Ptr goes out of scope, its destructor will be called, which will then indicate to the PtrManager that one less pointer is pointing at the address. If there are now 0 pointers pointing at it, the PtrManager will indicate to the dying Ptr object that it should clean up the address it points to. I didn't place the cleanup in the PtrManager because the pointer manager stores all of the addresses as void* pointers, and void* is undefined when you try to delete it.
So, I was really excited about my implementation, until I realized a large potential mistake: What if the smart pointer is pointing to something that is declared on the stack? It's not hard to imagine that happening. I create things on the stack and then give their address to a function all the time. Smart Pointers need to be smart enough to not delete something when it's on the stack, but yet be able to delete something when it is allocated on the heap. So, I looked around on the internet, but the only things I found on determining if an address is on the stack or the heap contained assembly code in them, and I didn't want to use assembly. I want QubLib to be cross-platform, so I decided that wouldn't be the way to go. I also found out that some stacks will grow towards 0 and some grow towards positive infinity. So, I created a new class called StackInfo that enables me to tell the direction that the stack is growing simply by creating two integers and checking to see which direction their memory addresses are progressing. After that I can tell if an address is on the stack if it is within the bounds of the top of the stack and the base of the stack. I don't know the base of the stack, but I can create an integer value that will be the top of the stack and I can use that with the stack growing direction to determine if the value is on the stack or the heap. I think this method works. I tried it on both my Windows 7 and Ubunto 10.04 LTS machines, but those are both running on the same processor. I wish I had a device with a different sort of processor that I could run these things on. Any suggestions? Like I said, last night it worked like a charm, but I'm curious what sort of pitfalls I would probably run into.
No comments:
Post a Comment