Boost logo

Boost Users :

From: Stephen Torri (storri_at_[hidden])
Date: 2007-05-17 10:24:16


On Thu, 2007-05-17 at 11:16 +0200, Hughes, James wrote:
> > -----Original Message-----
> > From: boost-users-bounces_at_[hidden]
> > [mailto:boost-users-bounces_at_[hidden]] On Behalf Of
> > Stephen Torri
> > Sent: 16 May 2007 23:52
> > To: boost-users
> > Subject: [Boost-users] Best way to create a class using the
> > singletonpattern and shared pointers?
> >
> > Here is a function that I am trying to understand why its
> > giving me a error via valgrind of "Invalid read of size 4".
> >
> > 16: Trace_State::ptr_t Trace_State::Instance()
> > 17: {
> > 18: // Lock the resource?
> > 19: if ( m_instance.get() == 0 )
> > 20: {
> > 21: m_instance = Trace_State::ptr_t ( new
> > Trace_State() );
> > 22: }
> > 23:
> > 24: // Unlock the resource?
> > 25:
> > 26: return m_instance;
> > 27: }
>
> Sorry, I don't have an answer to your specific question, but why would
> you need to use a shared_ptr on a singleton anyway? You have no real
> need to deallocate a singleton instance, so no need for a
> shared_ptr....perhaps use a reference (See Meyers singletons)
>
> Oh, hold on a sec....is it valid to call get() on an unassigned
> shared_ptr, which you are doing in the instance function?
>
> James

Back when I first learned about the singleton pattern I used a standard
pointer similar to this example:

  class Singleton
  {
  public:
      static Singleton* Instance();
  protected:
      Singleton();
      Singleton(const Singleton&);
      Singleton& operator= (const Singleton&);
  private:
      static Singleton* pinstance;
  };

Now I am trying to be a good programmer and keep track of my pointers.
So I decided that I should replace the pointer with a shared_ptr.

In regards to the validity of calling get() on an unassigned shared_ptr
I thought that if a shared_ptr was declared in the header and no call is
given to any constructor that the default constructor would be used.
Therefore the shared_ptr would have a value of 0x0.

Stephen


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