Boost logo

Boost :

From: scleary_at_[hidden]
Date: 2002-07-16 12:34:45


> From: Philippe A. Bouchard [mailto:philippeb_at_[hidden]]
> "David B. Held" <dheld_at_[hidden]> wrote in message
> news:ah0cl8$tqu$1_at_main.gmane.org...
> >
> > I'm no expert on smart
> > pointers, but it seems that std::auto_ptr could easily have taken this
> > route. My question is: why did it not?
>
> Because the mutable modifier shouldn't be used for regular members. It is
> reserved for cached, temporary buffers, etc. This is why 'mutable' is
part
> of the class name: it is not used for cache but for speed optimization.

This usage of 'mutable' was rejected because it has the side effect that two
copies of an object are not equivalent. This, in turn, can cause nasty
side-effects if you use mutable_ptr with Standard containers and algorithms.

While you can usually get away with using it in containers (although it's
not technically portable), the real problem comes in using it with
algorithms:
  struct T { int id; };
  struct compare_T_ids_indirect {
      bool operator()(const mutable_ptr<T> & x, const mutable_ptr<T> & y)
const
      { return (x->id < y->id); }
  };

  std::vector<mutable_ptr<T> > v;
  ; // Fill v with T's
  std::sort(v.begin(), v.end(), compare_T_ids_indirect());

See the GOTW link posted earlier, where Herb points out that a common
implementation of 'sort' uses a pivot element local to the function, and is
not copied back into the sequence. If you actually do the above on such an
implementation, you will mysteriously "lose" some of your vector elements!

A quick search through the C++ library shipped with my compiler shows that
this problem will occur on sort, partition, and merge. Whether it will
occur on other functions or platforms is entirely
implementation-dependent...

        -Steve


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk