Re: Adding pointer to container
On Wed, 11 Jun 2008 03:36:07 -0700 (PDT), tech rote:
Hi, i have a std::vector of pointers to base classes say
std::vector<element*> m_elements;
how do i make the followin exception safe
function()
{
element* e= new DerivedElement;
m_elements.push_back(element);
}
You question includes more than one aspect:
1. STL is designend for values only (a.k.a. 'value semantics'), not
objects or pointers to objects. Put simply, STL doesn't work with
pointers.
2. You cannot practically 'handle' Out-Of-Memory (OOM). You can do it
in theory but it always boils down to terminating the application.
Therfore you need not care for OOM conditions or even try to catch
std::bad_alloc in your application code. Some OS (e.g. Linux) never
indicate OOM.
3. If you still want an 'exception safe' push_back() for vector use
reserve() to 'pre-order' enough capacity. Something like the following
(BTW, note the difference between reserve() and resize()):
if (vec.capacity() == vec.size()) {
vec.reserve(vec.capacity() * 2);
}
vec.push_back(new Element());
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch