Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<blockquote> <p>Now, the question is, are there any disadvantages to this solution?</p> </blockquote> <p>Yes. See for instance, this entry in the c++ faq on the static initialization order fiasco. <a href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14" rel="nofollow">http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.14</a> tldr? Essentially, you have no control over what order static objects (such as Foo above) get initialized in, any assumptions about the order (eg. initializing one static object with values from another) will result in Undefined Behaviour.</p> <p>Consider this code in my app.</p> <pre><code>#include "my_project/library/Foo.h" static int whoKnowsWhatValueThisWillHave = Foo::some_value; int main() { return whoKnowsWhatValueThisWillHave; } </code></pre> <p>There are no guarantees on what I am returning from main() here.</p> <blockquote> <p>The user can create other instances of this library if they choose, for whatever reason. But no copying would be allowed. One instance would be provided for them by default. This is a requirement.</p> </blockquote> <p>Not really, no... Since all of your data is static, any new instances are essentially empty shells pointing to the same data. Basically, you have a copy.</p> <blockquote> <p>I feel like I'm doing something that C++ wasn't meant to do because Visual Studio's IntelliSense keeps freaking out on me and thinks my_project::Foo isn't declared. Could it be because both the object and the class are called Foo even though they're in different namespaces?</p> </blockquote> <p>You are! Suppose I add this line to my code:</p> <p>using namespace ::my_project::library;</p> <p>what does 'Foo' resolve to now? Maybe this is defined in the standard, but at the very least, it is confusing.</p> <blockquote> <p>I can use the . syntax instead of ::. But that's a personal style thing.</p> </blockquote> <p>Don't fight the language. If you want to code in Python or Java syntax, use Python or Java (or Ruby or whatever)...</p> <blockquote> <p>Should I simply stick to the singleton design pattern as an alternative solution? Are there any alternative solutions?</p> </blockquote> <p>Yes, the Singleton is a good one, but you should also consider whether you actually need a singleton here. Since your example is only syntactic, it is hard to say, but maybe it would be better to use dependency injection or something similar to minimize/eliminate tight couplings between classes.</p> <p>Hopefully I haven't hurt your feelings :) It's good to ask questions, but obviously you already know that!</p>
 

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