Thread overview
Equivalent of C++ function-scope static initialization
Mar 02, 2015
Mark Isaacson
Mar 02, 2015
Ali Çehreli
Mar 03, 2015
Mark Isaacson
March 02, 2015
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?
March 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

March 03, 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 :).


> > 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.