[geos-devel] GeometryFactory - call for explanation

Mateusz Łoskot mateusz at loskot.net
Sun Apr 2 10:31:15 EDT 2006


strk at refractions.net wrote:
> On Fri, Mar 31, 2006 at 10:31:33AM +0200, Mateusz Å?oskot wrote:
>> strk at refractions.net wrote:
>>> I'm in favour of this, but it would be an immutable instance, 
>>> using a FLOATING PrecisionModel.
>> Do you mean you want to provide single global common factory?
> 
> Yes, but not preventing the construction of new ones. BTW, in case we
>  use shared_ptr<> should we prevent direct construction by using the
>  'named construction idiom' ?
> 

Do you mean to prevent user from creating instance of factory using new
operator?

Foo* p = new Foo();

AFAIK there is no special recommendation to use named ctor idiom when
using smart pointers.
It depends on the design but what we can be sure of is explicit
construction of every shared_ptr. Does mean, you will get compiler
errors when trying to do something like this:

void foo(boost::shared_ptr<Foo> p);

// Somewhere in the program
Foo* p = new Foo(2);
foo(p);
delete p;

error: cannot convert parameter 1 from 'Foo *' to 'boost::shared_ptr<T>'
Constructor for class 'boost::shared_ptr<T>' is declared 'explicit'

Another question is if objects we are going to manage with smart
pointers will always live on the heap.
If they will, then it's a good practice to make ctor private/protected
and expose only named ctor e.g. Foo::create()
Certainly, the create() constructor should return shared_ptr.

Please, not, there are quite many possibilities, so I'd prefer to
discuss every such in details than to answer "what to do in general" :-)

Here is small example ready to experiment with:

/////////////////////////////////////////////////////////////////
#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;

class Foo
{
public:
   ~Foo() { cout << "Foo::~Foo()\n"; }
   static boost::shared_ptr<Foo> create(int x)
   {
      boost::shared_ptr<Foo> ps(new Foo(x));
      return ps;
   }
   int x() const { return x_; }

private:
   int x_;
   Foo() : x_(0)  { cout << "Foo::Foo()\n"; }
   Foo(int x) : x_(x)  { cout << "Foo::Foo(int x)\n"; }
};

int main()
{
   boost::shared_ptr<Foo> ptr = Foo::create(8);
   cout << ptr->x() << endl;

   return 0;
}
/////////////////////////////////////////////////////////////////

Cheers
-- 
Mateusz Łoskot
http://mateusz.loskot.net



More information about the geos-devel mailing list