Question regarding D v.0110
Steven Schveighoffer
schveiguy at gmail.com
Mon Jul 13 12:25:33 UTC 2020
On 7/13/20 3:45 AM, Remi wrote:
> Thanks for the suggestions regarding the cyclic dependency, I figured
> out a way to remove the cycles. It was mostly doing this in each class:
>
>> class Foo
>> {
>> static Rand rand;
>> public static this()
>> {
>> rand = new Rand;
>> }
>> public static void setRandSeed(long n)
>> {
>> rand.setSeed(n);
>> }
>> }
>
> which I replaced with
>
>> class Foo
>> {
>> static Rand rand;
>> public static void setRandSeed(long n)
>> {
>> if (!rand)
>> {
>> rand = new Rand;
>> }
>> rand.setSeed(n);
>> }
>> }
>
> Simple and it works!
This is slightly different. In the first case, rand is initialized even
if you don't call setRandSeed. A more correct approach:
public static Rand rand()
{
static Rand result;
if(result is null)
result = new Rand;
return result;
}
Though it depends on usage -- perhaps a Rand is useless without a seed set?
As I suspected, the static ctor could easily be marked standalone (as
in, it can't be part of a cycle, because it doesn't depend on any other
module to run). This is quite frequently one of the biggest problems
with D's static ctors.
-Steve
More information about the Digitalmars-d
mailing list