On Mon, 3 Dec 2001, Richard Bell wrote:
> I'm using C++ for my Palm OS application and was wondering if using new and
> delete for creating/destroying pointers to classes is the right approach. I
> would rather create a handle and lock unlock it when I access the class, are
> there any issues with this I should be aware of? I'm thinking that the
> following code would work:
>
> MemHandle h;
> MyClass *pClass;
>
> h=MemHandleNew(sizeof(MyClass));
> if (h)
> {
> pClass = (MyClass*) MemHandleLock(h);
> pClass->MyClass(); // call the constructor
> MemHandleUnlock(h);
> }
>
> ...
> if (h)
> {
> pClass = (MyClass*) MemHandleLock(h);
> pClass->~MyClass(); // call the destructor
> MemHandleUnlock(h);
> MemHandleFree(h);
> }
I don't think you can call a C++ constructor like that--think you need to
overload the placement new operator to explicitly construct memory.
If you really want handle behavior, you might think about defining some
handle classes (MyClassHandle for each MyClass) so you don't have to cast
things and explicitly call destructors etc. all over the place. These
could provide lock/unlock methods or even auto-locking around method
calls.
But consider just using direct pointers. The handle business is an OK hack
if you're really concerned about memory fragmentation, but that just isn't
an issue on today's 8-Mb devices, particularly for small allocations like
individual objects, and it's a lot of hassle.
Jake
--
For information on using the Palm Developer Forums, or to unsubscribe, please see
http://www.palmos.com/dev/tech/support/forums/