constexpr initializing static member using static function

The Standard requires (section 9.4.2): A static data member of literal type can be declared in the class definition with the constexpr specifier; if so, its declaration shall specify a brace-or-equal-initializer in which every initializer-clause that is an assignment-expression is a constant expression. In your “second attempt” and the code in Ilya’s answer, the declaration … Read more

How to force a static member to be initialized?

Consider: template<typename T, T> struct value { }; template<typename T> struct HasStatics { static int a; // we force this to be initialized typedef value<int&, a> value_user; }; template<typename T> int HasStatics<T>::a = /* whatever side-effect you want */ 0; It’s also possible without introducing any member: template<typename T, T> struct var { enum { … Read more

c++ access static members using null pointer

TL;DR: Your example is well-defined. Merely dereferencing a null pointer is not invoking UB. There is a lot of debate over this topic, which basically boils down to whether indirection through a null pointer is itself UB. The only questionable thing that happens in your example is the evaluation of the object expression. In particular, … Read more

C++ Static member initialization (template fun inside)

This was discussed on usenet some time ago, while i was trying to answer another question on stackoverflow: Point of Instantiation of Static Data Members. I think it’s worth reducing the test-case, and considering each scenario in isolation, so let’s look at it more general first: struct C { C(int n) { printf(“%d\n”, n); } … Read more

Do static members ever get garbage collected?

No, static members are associated with the Type, which is associated with the AppDomain it’s loaded in. Note that there doesn’t have to be any instances of HasStatic for the class to be initialized and the shared variable to have a reference to a List<string>. Unless you’re considering situations where AppDomains get unloaded, static variables … Read more

Error message Strict standards: Non-static method should not be called statically in php

Your methods are missing the static keyword. Change function getInstanceByName($name=””){ to public static function getInstanceByName($name=””){ if you want to call them statically. Note that static methods (and Singletons) are death to testability. Also note that you are doing way too much work in the constructor, especially all that querying shouldn’t be in there. All your … Read more

How to initialize static variables

PHP can’t parse non-trivial expressions in initializers. I prefer to work around this by adding code right after definition of the class: class Foo { static $bar; } Foo::$bar = array(…); or class Foo { private static $bar; static function init() { self::$bar = array(…); } } Foo::init(); PHP 5.6 can handle some expressions now. … Read more