How do you lazily construct a singleton object thread-safely? [duplicate]

Here’s Meyer’s singleton, a very simple lazily constructed singleton getter: Singleton &Singleton::self() { static Singleton instance; return instance; } This is lazy, and C++11 requires it to be thread-safe. In fact, I believe that at least g++ implements this in a thread-safe manner. So if that’s your target compiler or if you use a compiler … Read more

Python class member lazy initialization

You could use a @property on the metaclass instead: class MyMetaClass(type): @property def my_data(cls): if getattr(cls, ‘_MY_DATA’, None) is None: my_data = … # costly database call cls._MY_DATA = my_data return cls._MY_DATA class MyClass(metaclass=MyMetaClass): # … This makes my_data an attribute on the class, so the expensive database call is postponed until you try to … Read more

why is Lazy constrained to static contexts?

Object initializers outside a constructor (or method) has to refer to static members only. This is because the instance hasn’t been constructed until the constructor is run, hence the fields are not “ready yet” and therefor cannot be referenced. Static fields work because they are initialized before fields. Note that the error isn’t caused by … Read more

Are lazy vars in Swift computed more than once?

lazy vars are only calculated once, the first time you use them. After that, they’re just like a normal variable. This is easy to test in a playground: class LazyExample { var firstName = “John” var lastName = “Smith” lazy var lazyFullName : String = { [unowned self] in return “\(self.firstName) \(self.lastName)” }() } let … Read more

Thread safe lazy construction of a singleton in C++

Basically, you’re asking for synchronized creation of a singleton, without using any synchronization (previously-constructed variables). In general, no, this is not possible. You need something available for synchronization. As for your other question, yes, static variables which can be statically initialized (i.e. no runtime code necessary) are guaranteed to be initialized before other code is … Read more

Lazy Var vs Let

This is the latest scripture from the Xcode 6.3 Beta / Swift 1.2 release notes: let constants have been generalized to no longer require immediate initialization. The new rule is that a let constant must be initialized before use (like a var), and that it may only be initialized: not reassigned or mutated after initialization. … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)