Boost logo

Boost Users :

From: Peter Dimov (pdimov_at_[hidden])
Date: 2003-03-28 13:01:55


Maurizio Colucci wrote:
> Hello,
>
> I am a newbie user of boost.
>
> I have a question about boost::shared_ptr. Suppose you have a
> polimorphic list:
>
> class entity{ ...};
>
>
> class simple_entity : public entity{
> public:
> uint id;
> simple_entity(uint i) : id(i) {}
> };
>
> int main(){
> list<shared_ptr<entity> > l;
> ...
>
>
> I noticed the following code doesn't compile
>
> l.push_back(new simple_entity(1));
>
> too bad, because it was very easy to read, and very similar to the
> behavior if standard pointers (not to speak about similarity to Java
> and C#). So I am forced to do
>
> l.push_back(shared_ptr<entity> (new simple_entity(1)));

The idiomatic way to write the above is to use a named variable:

  shared_ptr<entity> pe(new simple_entity(1));
  l.push_back(pe);

as explained in

http://www.boost.org/libs/smart_ptr/shared_ptr.htm#BestPractices

If you want to save typing, consider adding

  static shared_ptr<simple_entity> create(int id)
  {
      shared_ptr<simple_entity> ps(new simple_entity(id));
      return ps;
  }

to simple_entity, allowing you to write

  l.push_back(simple_entity::create(1));

If entity objects are always supposed to live on the heap, you now have the
option to make the simple_entity constructor private or protected, leaving
'create' as the only way to obtain a simple_entity.


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net