digitalmars.D.learn - Equivalent of C++ function-scope static initialization
- Mark Isaacson (13/13) Mar 02 2015 I'm looking for the D equivalent of:
- =?UTF-8?B?QWxpIMOHZWhyZWxp?= (12/20) Mar 02 2015 immutable string bar;
- Mark Isaacson (5/15) Mar 02 2015 New as of C++11. All function-scope statics are guaranteed to be
I'm looking for the D equivalent of: //C++ void foo() { static string bar = painfulToInitialize(); //Always returns the same value /* A bunch of code */ } I don't need the thread-safety that C++ provides in that case, though it wouldn't hurt. I'm essentially trying to memoize the result of painfulToInitialize() between calls to foo. I could use std.functional.memoize, but that seems like a syntactic burden. Unfortunately, I cannot compute the value at compile time. What's the idiomatic way of doing something like this?
Mar 02 2015
On 03/02/2015 02:06 PM, Mark Isaacson wrote:I'm looking for the D equivalent of: //C++ void foo() { static string bar = painfulToInitialize(); //Always returns the same value /* A bunch of code */ }immutable string bar; shared static this() { bar = painfulToInitialize(); } void foo() { } When needed, 'bar' can be mutable as well but you have to take care of synchronization yourself in that case.I don't need the thread-safety that C++ provides in that case,I am not aware of such safety. (?) Is that a newer C++ feature? Ali
Mar 02 2015
On Monday, 2 March 2015 at 23:07:30 UTC, Ali Çehreli wrote:immutable string bar; shared static this() { bar = painfulToInitialize(); } void foo() { }Clever :).New as of C++11. All function-scope statics are guaranteed to be initialized in a thread-safe manner. Exactly one thread will initialize the variable the first time the function is called.I don't need the thread-safety that C++ provides in that case,I am not aware of such safety. (?) Is that a newer C++ feature? Ali
Mar 02 2015