Re: Removing the assignable requirement from stl list elements
Kevin Lin <kevin.ic@gmail.com> wrote:
I've been studying implementations of linked lists in sgi-stl and
updated versions in stlport, hoping to adapt one for my own needs. One
thing that caught my eye in the sgi implementation is the availability
of additional push_back and insert signatures in both list and slist:
void push_back();
void insert(iterator i);
To me this seems like a very reasonable extension that should allow:
typedef std::list< std::auto_ptr<int> > list_type;
list_type mylist;
list_type::iterator ptrIter = mylist.insert(mylist.begin());
ptrIter->reset(new int());
In the actual implementation, however, both stlport and sgi-stl just
translates the insert(i) call to insert(i, value_type()), thereby
forcing value_type to be const copyable.
So it seems like the implementers started to put in support for default
constructible but not assignable list elements, then decided that it's
a bad idea. Why is this so? Is the above code too dangerous to allow?
There are better and safer alternatives to using auto_ptr or even raw
ptrs in list. boost::shared_ptr and boost::intrusive_ptr if applicable
come to mind. TR1::shared_ptr as well.
what about
inline bool is_even(std::auto_ptr<int> x) {return !( *x & 1);}
list_type listing;
// fill it with the extension
iisting.remove_if(is_even);
All your even data is removed AND all the odd data is replaced by
auto_ptr<int>()!! essentially removed...Neat:(:(
if shared_ptr<int> was the value_type of the list the results of the
above snipplet would be correct. This may be obvious but other gotchas
will creep into anything but trivial code and produce a maintaince
nightmare that is easily avoided using a proper smart pointer or garbage
collection if available and tunable...
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]