Christian Meier wrote:
"John Ratliff" <us**@example.net> schrieb im Newsbeitrag
news:j8kKe.236394$x96.154050@attbi_s72...
When I dereference a pointer, does it make a copy of the object?
Say I had a singleton, and wanted an static method to retrieve it from
the class.
class foo {
private:
static foo *bar;
foo() {} // no public creation!
public:
~foo() { delete bar; }
foo &instance() { return *bar; }
IMHO instance should be a static function.
Apologies. I quickly typed an example. In my actual class, instance is a
static function. I also just realized the destructor is deleting bar,
which would be very bad if the object were copy constructed. Should be
delete this, or have an overridden undefined copy constructor.
};
foo foo::bar = new foo;
try foo* foo::bar = new foo;
Typo again here.
try something like that:
static foo* getInstance() { if (!bar) bar = new foo; return bar; };
....
foo* foo::bar = 0;
...
int main()
{
foo* f = foo::getInstance();
}
I'd prefer to return a reference since no copy is created.
I also thought about the null object pattern, but the overhead of
creating the object at startup is less than the overhead of the if tests.
However, I have a new (but related) problem. Let's say I have another
class that uses this singleton extensively. There are multiple instances
of this class running around (5 to be precise). Multiple functions in
this class will need to use this singleton. What happens if I try to
include a static reference to the singleton in the multiple-instance
class? Something like this:
class a_singleton {
private:
static a_singleton *singleton;
a_singleton() {} // singleton!
public:
a_singleton(const a_singleton &); // singleton
~a_singleton() { delete this; }
static &a_singleton instance() { return *singleton; }
};
a_singleton *a_singleton::singleton = new a_singleton;
class b_5instancer {
private:
static a_singleton &singleton;
}
a_singleton &b_5instancer::singleton = a_singleton::instance();
Is this possible? Two questions spring to mind.
a) can you have a static class member reference? If not, I suppose it
could be a pointer.
b) Is there any way to know which would be initialized first. It seems
like unless I used the null object pattern, there's a good chance I
could be dereferencing an unknown (very possibly uninstantiated)
pointer to a_singleton when calling instance() during runtime
creation.
If this is not possible, would it work with a static reference (or
pointer if static member references are not possible) if a_singleton
used the null object pattern?
Thanks,
--John Ratliff