a**********2 发帖数: 340 | 1 如果singleton pattern的getInstance()方法定义成这样有问题吗?
class A
{
public:
static A* getInstance()
{
static A a;
return &a;
}
}; |
j******c 发帖数: 294 | 2 This is wrong. google singleton, you should get a lot of correct sample
codes.
【在 a**********2 的大作中提到】 : 如果singleton pattern的getInstance()方法定义成这样有问题吗? : class A : { : public: : static A* getInstance() : { : static A a; : return &a; : } : };
|
h******3 发帖数: 351 | 3 at least the definition of
static A a
should be put under class instead of public method
【在 a**********2 的大作中提到】 : 如果singleton pattern的getInstance()方法定义成这样有问题吗? : class A : { : public: : static A* getInstance() : { : static A a; : return &a; : } : };
|
v*******7 发帖数: 187 | 4 I forgot, but some how it should be like this:
class Singleton{
public:
static Singleton * getInstance() {
if (_instance == NULL) {
_instance = new Singleton;
}
return _instance;
}
private:
static Singleton _instance;
Singleton();
~Singleton();
}
I forgot the details, but I think the above is the main idea of Singleton. |
c******n 发帖数: 4965 | 5 I don't see a problem with this
if you compile this code with gcc, and then decompile the resulting
code, the assembley looks like:
lock(some_lock)
if ( not_initialized ) {
a = new A();
not_initialized = false;
}
unlock(some_lock)
in fact, for the java version, the book "effective java" actually
recommends the idiom
class A {
static A ins = new A();
static A getInstance() { return ins;}
}
the java version has a bigger problem though: you can't control when
the ins is initialized, thus agains the goal of "lazy initialization"
of singleton pattern
【在 a**********2 的大作中提到】 : 如果singleton pattern的getInstance()方法定义成这样有问题吗? : class A : { : public: : static A* getInstance() : { : static A a; : return &a; : } : };
|