循环依赖不好:
struct Singleton2;
struct Singleton1 {
static Singleton1 const& get() {
static Singleton1 _instance;
return _instance;
}
private:
Singleton1();
Singleton2 const& _s2;
};
struct Singleton2 {
static Singleton2 const& get() {
static Singleton2 _instance;
return _instance;
}
private:
Singleton2();
Singleton1 const& _s1;
};
Singleton1::Singleton1() : _s2(Singleton2::get()) { }
Singleton2::Singleton2() : _s1(Singleton1::get()) { }
int main()
{
auto& s1 = Singleton1::get();
auto& s2 = Singleton2::get();
}
将导致失败(请参阅http://liveworkspace.org/code/4rPFDo$0)。
就像在所有需要打破循环的情况下一样,至少让链条中的一个环节变得懒惰。
通过在构造过程中不需要引用另一个单例,以明显的方式解决它:
struct Singleton2;
struct Singleton1 {
static Singleton1 const& get() {
static Singleton1 _instance;
return _instance;
}
private:
Singleton1() {}
static Singleton2 const& getOther();
};
struct Singleton2 {
static Singleton2 const& get() {
static Singleton2 _instance;
return _instance;
}
private:
Singleton2() {}
static Singleton1 const& getOther();
};
Singleton2 const& Singleton1::getOther() { return Singleton2::get(); }
Singleton1 const& Singleton2::getOther() { return Singleton1::get(); }
int main()
{
auto& s1 = Singleton1::get();
auto& s2 = Singleton2::get();
}
或者使用 boost::optional、boost::flyweight 或自定义的“lazy_ptr”进行延迟初始化:https ://stackoverflow.com/a/878298/85371