Re: Rebirthing an object... just making sure
* "Tom?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W?W":
I have an object that represents a listbox on a GUI dialog. In order
to clear the listbox, I can simply delete the listbox and then create
another one. For instance:
// Snippet A
delete p_list;
p_list = new ListBox();
There's the alternative method though that avoids re-allocating memory:
// Snippet B
p_list->~ListBox();
::new(p_list) ListBox();
My question is as follows:
If you're able perform snippet A on a particular object, then are you
ALWAYS able to perform snippet B instead?
I think so, yes, but the two code snippets are not equivalent.
In the first snippet, if ListBox() throws, the listbox object's memory
has been deallocated. In the second snippet, the memory has not been
deallocated. And here there's no easy way to deallocate that memory if
ListBox() throws.
Secondly, I had to check the standard about whether the second snippet
correctly handles a virtual destructor for the case of p_list pointing
to an instance of a derived class. Code that requires standard-checking
is a little ungood for maintainance. And in general, too "clever" code.
See I can't think of any reason why Snippet B wouldn't always work
perfectly... but for some reason it strikes me as one of those
situations where you might overlook something and only realise it a week
later, so I thought I'd check with you guys.
In addition to above comments, clearing a listbox that way could lead to
on-screen flicker, the cost of dynamic allocation in the context of GUI
operations is generally negligible, relatively speaking, and the only
dynamic allocation you avoid is for the listbox object itself, not for
constituents that are referred via pointers or handles.
Use the listbox'es clear function.
Don't optimize prematurely.
Cheers, & hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?