I have an PalmOS C++ application with code like the following:
//-------------------------------------------------------------
void TPrinterUtil::ReadConfiguration() { TPrinterData& Data = * new TPrinterData(*dbName); // do something with Data delete &Data; }
//-------------------------------------------------------------
I know that these two lines seem somewhat strange, but the fact is, they compile and run and, apparently, do their work as they should. However, one of my coworkers pointed to me it was easier, and safer, to write that code like this:
//-------------------------------------------------------------
void TPrinterUtil::ReadConfiguration() { TPrinterData Data(*dbName); // do something with Data // Data need not be explicitly destroyed }
//-------------------------------------------------------------
At first, I didn't see what could be the difference, but he (my coworker) told me my original code might not be destroying the memory block pointed to by Data, but something else, like system memory or unallocated space. Obviously, that freaked me out completely.
I need your opinion on this. Does this code do what my coworker says? If it does, I'm afraid I will need to rewrite most of the code in my application, and that scares me a lot!
Both versions should be OK. Yours has the benefit of not eating up precious stack space; his has the benefit of being safer (you don't have to worry about the allocation failing, or of the object being leaked by exiting the function before calling delete).
Your coworker's explanation as to why your approach is wrong seems bogus to me. I'm not sure what he's getting at with his comments about "system memory" or "unallocated space".
However, your use of references here is definitely non-standard, and I'm not even 100% sure that it's correct. For instance, what if operator new() returns NULL? What does Data refer to? What does &Data resolve to? I know what happens with the compilers I use from personal experience, but I'm not sure that the C++ spec says. Personally, I'd use the following:
void TPrinterUtil::ReadConfiguration()
{
TPrinterData* Data = new TPrinterData(*dbName);
// do something with Data
delete Data;
}or, better yet:
void TPrinterUtil::ReadConfiguration()
{
auto_ptr<TPrinterData> Data = new TPrinterData(*dbName);
// do something with Data.get()
// Data need not be explicitly destroyed
}-- Keith
-- For information on using the Palm Developer Forums, or to unsubscribe, please see http://www.palmos.com/dev/support/forums/
