Re: What is the best way to clear a std::set containing dynamically
allocated pointers?
Organization: http://groups.google.com
References: <1194996639.554675.158280@57g2000hsv.googlegroups.com>
<1195069288.464581.169430@y27g2000pre.googlegroups.com>
<6a972dff-101c-43cc-b026-2d2ee29392a3@l22g2000hsc.googlegroups.com>
Content-Type: text/plain; charset=ISO-8859-1
X-Clcppm-Sequence: 9873
X-Original-Date: Tue, 20 Nov 2007 08:49:17 -0800 (PST)
X-Submission-Address: c++-submit@netlab.cs.rpi.edu
On Nov 16, 11:24 pm, Olivier Langlois <olangl...@sympatico.ca> wrote:
void foo()
{
MySet mySet = makeSet(/* ... */);
useSet(mySet);
// you will not get here if there was an exception
deletePointers(mySet);
}
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
be.
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:
class C
{
std::set<MyClass *> mySet;
/* possibly other data */
public:
C(/* some input */)
: /* some initialization that MAY THROW */
{
/* some more code that MAY THROW */
}
~C()
{
/* 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.
Ali
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]