singleton pattern, return sole pt per reference

C

Chris Forone

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
 
F

Frank Birbacher

Hi!

Chris said:
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
 
C

Chris Forone

Frank said:
Hi!



Yes. Whenever you get a "this" you may return it.


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...

thanks a lot, chris
 
F

Frank Birbacher

Hi!

Chris said:
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>
::value> storage;

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

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

HTH,
Frank
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,211
Latest member
NelleWilde

Latest Threads

Top