Re: Adding pointer to container
Paavo Helde wrote:
Kai-Uwe Bux <jkherciueh@gmx.net> kirjutas:
Paavo Helde wrote:
rpbg123@yahoo.com (Roland Pibinger) kirjutas:
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.
It seems this is so ridiculous no one has bothered to answer. For
innocent bystanders I just remind that pointers are values in C++.
It is true, though, that pointers often require special handling when
dealing with containers. The most basic issue is illustrated by
std::map< char const *, some_type >
By default, the map will compare pointer values and not the strings
they represent. Very likely that is _not_ the desired behavior.
If you specify the map keys as pointers, they will be compared as
pointers, that's it.
Actually, nobody knows how they are compared. [20.3.3/8] just requires
std::less<T*> to yield a total order. There is no requirement whatsoever
that this order is related to or compatible with pointer comparison as per
[5.9/2].
I see nothing specific to STL here.
Huh? How is the default behavior of STL containers not specific to STL?
You could easily instruct the map to use the string comparison (if/when
needed) instead by providing an extra template argument for the map
declaration.
Of course, one _can_ do that. Often, one even _must_ do that. And sometimes,
people are not aware of the issue (which addresses your claim that it
is "easy": nothing is easy to do when you don't know that you should),
which is why related bugs come up in postings to this group where the
standard answer is: use std::string or provide a forwarding comparison
predicate.
IOW, STL does what it is told to do. It does not attempt to read your
mind. This is a Good Thing IMO.
I did not give an evaluation of any sort. I just felt the need to point out
that there are technical issues when using pointers in STL containers. I
did not suggest changing the STL nor did I claim that other alternatives
are preferable. To me, it's just a matter of awareness.
Best
Kai-Uwe Bux