Thread overview | |||||
---|---|---|---|---|---|
|
March 02, 2015 Equivalent of C++ function-scope static initialization | ||||
---|---|---|---|---|
| ||||
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 Re: Equivalent of C++ function-scope static initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Mark Isaacson | 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 Re: Equivalent of C++ function-scope static initialization | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | 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. |
Copyright © 1999-2021 by the D Language Foundation