468,554 Members | 1,087 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,554 developers. It's quick & easy.

singleton pattern, return sole pt per reference

its ok to return *this as reference (C++ FAQ L).

but is it also in singleton pattern (ctor example below)?

Timer* Timer::sole(0); // static

Timer& Timer::Get() // static
{
return sole ? *sole : *(sole = new Timer);
}

i think it isnt only if using new (std::nothrow),because of exeption
handling!?

HAND, Chris
Aug 16 '07 #1
3 1521
Hi!

Chris Forone schrieb:
its ok to return *this as reference (C++ FAQ L).
Yes.
but is it also in singleton pattern (ctor example below)?
Yes. Whenever you get a "this" you may return it.
Timer* Timer::sole(0); // static

Timer& Timer::Get() // static
{
return sole ? *sole : *(sole = new Timer);
}
I don't see any "this*" here. And "static" functions do not have a
"this" pointer, anyway. Your code is fine but I don't understand your
question here.

Frank
Aug 16 '07 #2
Frank Birbacher schrieb:
Hi!

Chris Forone schrieb:
>its ok to return *this as reference (C++ FAQ L).

Yes.
>but is it also in singleton pattern (ctor example below)?

Yes. Whenever you get a "this" you may return it.
>Timer* Timer::sole(0); // static

Timer& Timer::Get() // static
{
return sole ? *sole : *(sole = new Timer);
}

I don't see any "this*" here. And "static" functions do not have a
"this" pointer, anyway.
yes, but it returns a reference from a pointer. and if i use "new
(std::nothrow)" it returns a reference from a 0-pointer (bad in C++ FAQ L)

Your code is fine but I don't understand your
question here.
if the code is fine, no more question...
>
Frank
thanks a lot, chris
Aug 16 '07 #3
Hi!

Chris Forone schrieb:
yes, but it returns a reference from a pointer. and if i use "new
(std::nothrow)" it returns a reference from a 0-pointer (bad in C++ FAQ L)
Yeah, right. Bad bad. Hmm, but you could reserve memory in advance:

#include <boost/type_traits.hpp>
using namespace boost;

Foo& getInstance()
{
//use static POD
static bool initialized = false;
static aligned_storage<sizeof(Foo), alignment_of<Foo>
::valuestorage;

if(!initialized)
{
//construct Foo in storage
new (&storage) Foo();
initialized = true;
}

//return instance from storage
return *reinterpret_cast<Foo*>(&storage);
}

HTH,
Frank
Aug 16 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Alicia Roberts | last post: by
13 posts views Thread by William Stacey | last post: by
13 posts views Thread by Robert W. | last post: by
5 posts views Thread by tobias.sturn | last post: by
14 posts views Thread by rob | last post: by
3 posts views Thread by dischdennis | last post: by
10 posts views Thread by Chris Forone | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.