Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The cyclic dependency is bad:</p> <pre><code>struct Singleton2; struct Singleton1 { static Singleton1 const&amp; get() { static Singleton1 _instance; return _instance; } private: Singleton1(); Singleton2 const&amp; _s2; }; struct Singleton2 { static Singleton2 const&amp; get() { static Singleton2 _instance; return _instance; } private: Singleton2(); Singleton1 const&amp; _s1; }; Singleton1::Singleton1() : _s2(Singleton2::get()) { } Singleton2::Singleton2() : _s1(Singleton1::get()) { } int main() { auto&amp; s1 = Singleton1::get(); auto&amp; s2 = Singleton2::get(); } </code></pre> <p>Will result in a failure (see <a href="http://liveworkspace.org/code/4rPFDo$0" rel="nofollow noreferrer">http://liveworkspace.org/code/4rPFDo$0</a>). </p> <p>Like in all cases where you need to break cycles, make at least one link in the chain <strong><em>lazy</em></strong>.</p> <p>Solve it in the obvious way by not requiring a reference to the other singleton during construction:</p> <pre><code>struct Singleton2; struct Singleton1 { static Singleton1 const&amp; get() { static Singleton1 _instance; return _instance; } private: Singleton1() {} static Singleton2 const&amp; getOther(); }; struct Singleton2 { static Singleton2 const&amp; get() { static Singleton2 _instance; return _instance; } private: Singleton2() {} static Singleton1 const&amp; getOther(); }; Singleton2 const&amp; Singleton1::getOther() { return Singleton2::get(); } Singleton1 const&amp; Singleton2::getOther() { return Singleton1::get(); } int main() { auto&amp; s1 = Singleton1::get(); auto&amp; s2 = Singleton2::get(); } </code></pre> <p>Alternatively delay-initialize using boost::optional, boost::flyweight or a custom 'lazy_ptr': <a href="https://stackoverflow.com/a/878298/85371">https://stackoverflow.com/a/878298/85371</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload