www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Equivalent of C++ function-scope static initialization

reply "Mark Isaacson" <turck11 hotmail.com> writes:
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
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
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
parent "Mark Isaacson" <turck11 hotmail.com> writes:
On Monday, 2 March 2015 at 23:07:30 UTC, Ali Çehreli wrote:
 immutable string bar;

 shared static this()
 {
     bar = painfulToInitialize();
 }

 void foo() {
 }
Clever :).
 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
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.
Mar 02 2015