Boost logo

Boost :

From: ERICSSON,JOHAN (A-Sonoma,ex1) (johan_ericsson_at_[hidden])
Date: 2001-11-16 11:53:30

-----Original Message-----
From: Jeff King [mailto:peff-boost_at_[hidden]]
Sent: Thursday, November 15, 2001 11:45 PM
To: boost_at_[hidden]
Subject: [boost] polymorphic containers

I'm considering a new poly_ptr class for boost; the intent is to aid in
the creation of heterogenous (polymorphic) containers.

// declare 'derived1' and 'derived2', both inheriting from 'parent'
int main() {
  typedef poly_ptr<parent> phandle;
  typedef std::vector<phandle> pvector;

  pvector v;

  v.push_back(phandle::create(new derived1));
  v.push_back(phandle::create(new derived2));

  for(pvector::iterator i = v.begin(); i != v.end(); ++i)

  return 0;

The syntax is a little funny (you must create either a NULL poly_ptr
with poly_ptr(), or you must use the static create() function); this is
because create() is a templated function that grabs the necessary type
info. You also still have to deal with the double dereference for the
iterator; I don't think it's possible to deal with this using standard
containers and not using a dereferencing iterator adaptor.

I'm using a poly_ptr template extensively within my code. I konw that you
have retracted your proposal but I just wanted to give my two cents.
1. Don't allow the poly_ptr to have a NULL value. This simplifies both the
implementation of poly_ptr and the client significantly. The client no
longer has to check for a NULL poly_ptr. If the client needs an optional
poly_ptr then it can use an optional class or something like that. This
restriction also, in my opinion, makes the poly_ptr act more like a value
semantic class. It is also more in the spirit of C++, not to supply a
default constructor if the default constructor places an object in a NULL
2. I didn't understand why you needed to use the create() function to create
a poly_ptr. I simply use a conversion constructor.
poly_ptr(const T& t):m_pT(t.Clone()){}
poly_ptr<parent> p(child());
a. This preserves the value-oriented semantics, as you are not taking
ownership of a naked pointer. You are copying a value into the poly_ptr.
This is the same way that the STL containers work. They copy values, they
don't take ownership.
b. Perhaps you needed the create() function to customize the signature of
the Clone() (clone(), copy(), Copy()) method...
Anyways, I think a poly_ptr object still has value over a broader variant
object. The usage of the poly_ptr is bound to be easier.
Also, I don't think the poly_ptr can be handled adequately by a policy based
smart pointer object. The semantics that I would like to see(value
semantics, copying to create), are so different from other pointers that the
policies would need to be quite complicated in order to allow the pointer to
act properly.

Boost list run by bdawes at, gregod at, cpdaniel at, john at