如果singleton pattern的getInstance()方法定义成这样有问题吗? class A { public: static A* getInstance() { static A a; return &a; } };
w*n
2 楼
求大神们指点 才几个月的记录 Citi FIA SPG都搞了 接下来搞个啥好 discover or freedom or sapphire?
j*c
3 楼
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; : } : };
b*u
4 楼
休息一阵吧。 [发表自未名空间手机版 - m.mitbbs.com]
h*3
5 楼
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; : } : };
i*g
6 楼
sigh 常逛本版免不了过几天就想申新卡
求大神们指点 才几个月的记录 Citi FIA SPG都搞了 接下来搞个啥好 discover or freedom or sapphire?
【在 w*****n 的大作中提到】 : 求大神们指点 : 才几个月的记录 : Citi FIA SPG都搞了 接下来搞个啥好 discover or freedom or sapphire?
v*7
7 楼
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.
d*g
8 楼
discover and freedom
c*n
9 楼
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; : } : };