Global runtime strings help

Steven Schveighoffer schveiguy at yahoo.com
Mon Sep 26 13:44:15 PDT 2011


On Mon, 26 Sep 2011 15:57:21 -0400, Jonathan Crapuchettes  
<jcrapuchettes at gmail.com> wrote:

> Thank you for the thought, but the problem here is that the file  
> containing the strings is only known at runtime from a command line  
> argument. I also have some global strings that need to be set from the  
> database.
>
> Thank you again,
> JC
>

Hm... interesting situation.

The issue is, you want them to be immutable at some arbitrary point in  
time, NOT before main is run.

With D the way it is, I think you are better off encapsulating that as  
private mutable storage backing public accessors:

module mystringdata;

private shared /* or __gshared */ string _mystringvalue = null;

void initializeStrings(dbconnection db, someFileSource f) // call this  
before using any of the strings
{
  // read the string from the db/file
   _mystringvalue = db.read("mystringdata");
   ...
}

@property string mystringvalue()
{
    assert(_mystringvalue !is null); // ensure it's valid before being used.
    return _mystringvalue;
}

// repeat for other values.

Otherwise, you could potentially circumvent the type system, but that  
results in undefined behavior.  I don't know how well that would work, but  
it might solve the problem for the current compiler implementation.

-Steve


More information about the Digitalmars-d-learn mailing list