[prev in list] [next in list] [prev in thread] [next in thread] 

List:       kde-devel
Subject:    Re: static class in c++
From:       Michael Goffioul <goffioul () imec ! be>
Date:       2001-04-23 8:43:16
[Download RAW message or body]

Charles Samuels wrote:
> 
> On Monday 23 April 2001 01:19 am, Greg Hulands wrote:
> > I am relatively new to c++ and my reference book does not seem to cover
> > this topic.
> >
> > I have a class Foo() but want to make it only to be instaniated once, so
> > when a new call to the class is made it returns the same object. So in the
> > implementation of Foo I have at the top of the file
> >
> > static Foo *foo = 0;
> >
> > In the constructor I then have
> >
> > Foo()
> > {
> >       if (!foo)
> >               foo = new Foo;
> >
> >       return foo;
> > }
> >
> > but this just makes a recursive call to the constructor as it has not
> > allocated space for the object. What memory allocation do i use in the
> > constuctor?
> 
> What you're looking for is 'foo = this;' instead of foo = new Foo;

You should use a singleton pattern instead.

class Foo
{
public:
	Foo();
	static Foo* self();
private:
	static Foo *foo;
}

Foo* Foo::foo = 0;

Foo* Foo::self()
{
	if (!foo)
		foo = new Foo();
	return foo;
}

Then to get the single object instance, use "Foo::self()" instead of
constructing a new object.

Michael.

-- 
------------------------------------------------------------------
Michael Goffioul		IMEC-DESICS-MIRA
e-mail: goffioul@imec.be	(Mixed-Signal and RF Applications)
Tel:    +32/16/28-8510		Kapeldreef, 75
Fax:    +32/16/28-1515		3001 HEVERLEE, BELGIUM
------------------------------------------------------------------
 
>> Visit http://master.kde.org/mailman/listinfo/kde-devel#unsub to unsubscribe <<

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic