这可以被认为是c++中单例类的有效实现吗?


#include <iostream>
using namespace std;
class Singleton {
public:
int val;
static int count;
Singleton() {
if (count == 1) throw 0;
Singleton::count++;
val = 100;
}
};
int Singleton::count = 0;
int main () {
try {
Singleton a, b;
} catch (...) {
cout << "errorn";
}
return 0;
}

计算创建的对象的数量,当count即将超过1时从构造函数抛出。从构造函数抛出是否会中止对象的创建?

c++ 11及以上版本:

将构造函数设为私有,并在静态函数中定义静态实例。它同步构造,所以对象只构造一次,不管有多少线程试图访问它:

class Singleton {
private:
Singleton() { /* ... */ }
public:
static auto& instance() {
static Singleton singleton;
return singleton;
}
};

Pre c++ 11:

在c++ 11 (c++ 03, c++ 98)之前,没有同步对象构造的标准方法。你需要使用特定于操作系统的技巧来使它工作。

如果你有一个单线程程序,因此不关心同步,你可以使用与上面相同的版本。

最新更新