Re: What is the best way to clear a std::set containing dynamically
Content-Type: text/plain; charset=ISO-8859-1
X-Original-Date: Tue, 20 Nov 2007 08:49:17 -0800 (PST)
On Nov 16, 11:24 pm, Olivier Langlois <olangl...@sympatico.ca> wrote:
MySet mySet = makeSet(/* ... */);
// you will not get here if there was an exception
There is no guarantee that you will get to the traversal code.
I do not think that I have an exception safe code problem. What I have
not specified in my original post is that my set is a data member of a
class and the set is cleared in the class destructor.
This is the same as Jorgen Grahn's reply.
My understand of
exception safety tells me doing so is as safe as using smart_ptr would
No it won't be. What you and Jorgen describe can work only sometimes.
The reason is, the destructor of the class that encapsulates the set
will not be executed unless the object is "constructed." That means,
when the constructor has completed:
std::set<MyClass *> mySet;
/* possibly other data */
C(/* some input */)
: /* some initialization that MAY THROW */
/* some more code that MAY THROW */
/* cleanup of mySet WILL NOT BE EXECUTED
if the constructor was not completed */
There are solutions for this; like using try/catch blocks in the
constructor body and around the initialization list, but I will leave
it to you to compare those workarounds to simply using a smart pointer
in the set.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]