Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You said that "creating one a second time would damage the whole application.". My response is: so don't make more then one. In C++, the type system is too weak to easily ensure this at compile-time. We can still write up a utility to approximate it at run-time, though.</p> <p>Note, though, that this in no way implies you should use a singleton. (You have zero need for a global; it's unfortunate the drones have associated single-instance with global). What you want is this:</p> <pre><code>#include &lt;stdexcept&gt; // inherit from this class (privately) to ensure only // a single instance of the derived class is created template &lt;typename D&gt; // CRTP (to give each instantiation its own flag) class single_instance { protected: // protected constructors to ensure this is used as a mixin single_instance() { if (mConstructed) throw std::runtime_error("already created"); mConstructed = true; } ~single_instance() { mConstructed = false; } private: // private and not defined in order to // force the derived class be noncopyable single_instance(const single_instance&amp;); single_instance&amp; operator=(const single_instance&amp;); static bool mConstructed; }; template &lt;typename T&gt; bool single_instance&lt;T&gt;::mConstructed = false; </code></pre> <p>Now you get an exception if the class is constructed more than once:</p> <pre><code>class my_class : private single_instance&lt;my_class&gt; { public: // usual interface (nonycopyable) }; int main() { my_class a; // okay my_class b; // exception } </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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