Re: Ideas for strong guarantee?
David Abrahams wrote:
If you really need the strong guarantee:
void func()
{
std::auto_ptr<Type> sp1(new Type());
std::auto_ptr<Type> sp2(new Type());
m_vec1.push_back(sp1.get()); //
try
{
m_vec2.push_back(sp2.get()); //
}
catch(...)
{
m_vec1.pop_back();
throw;
}
sp1.release();
sp2.release();
}
If I had one more vector the source code would grow up considerably
For example:
void func()
{
std::auto_ptr<Type> sp1(new Type());
std::auto_ptr<Type> sp2(new Type());
std::auto_ptr<Type> sp3(new Type());
m_vec1.push_back(sp1.get());
try
{
m_vec2.push_back(sp2.get());
}
catch(...)
{
m_vec1.pop_back();
throw;
}
try
{
m_vec3.push_back(sp3.get());
}
catch(...)
{
m_vec1.pop_back();
m_vec2.pop_back();
throw;
}
sp1.release();
sp2.release();
sp3.release();
}
Mybe an alternative is provide a "undo" operation in local class
descructor.
For example:
struct undo_push_back
{
typedef std::vector<Type*> containerType;
containerType m_vec;
bool m_bReleased;
undo_push_back(containerType & vec) : m_vec(vec),
m_bReleased(false) {}
~undo_push_back(containerType & vec)
{
if (!m_bReleased)
{
m_vec.pop_back();
}
}
void release()
{
m_bReleased = true;
}
};
void func()
{
std::auto_ptr<Type> sp1(new Type());
std::auto_ptr<Type> sp2(new Type());
std::auto_ptr<Type> sp3(new Type());
m_vec1.push_back(sp1.get());
undo_push_back undo1(m_vec1);
m_vec2.push_back(sp2.get());
undo_push_back undo2(m_vec2);
m_vec3.push_back(sp3.get());
undo1.release();
undo2.release();
sp1.release();
sp2.release();
sp3.release();
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]