www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Initializing constant AA and shared problems..

reply simendsjo <simendsjo gmail.com> writes:
I'm trying to initialize an AA, but initializing at definition fails, as  
do in a shared module ctor.

// how is this now constant?
//shared string[int] aa = [1: "a"]; // Error: non-constant expression  
[1:"a"]

// ok
string[int] aa2;
static this()
{
     aa2 = [1: "a"];
}

// The same with shared fails
// segfault
/+
shared string[int] aa3;
shared static this()
{
     aa3 = [1: "a"];
}
+/

// Using __gshared works though
__gshared string[int] aa4;
shared static this()
{
     aa4 = [1: "a"];
}

void main() {
     assert(aa4[1] == "a");
}
Mar 18 2012
parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
On Sun, Mar 18, 2012 at 02:50:00PM +0100, simendsjo wrote:
 I'm trying to initialize an AA, but initializing at definition
 fails, as do in a shared module ctor.
 
 // how is this now constant?
 //shared string[int] aa = [1: "a"]; // Error: non-constant
 expression [1:"a"]

This is a shortcoming in the current AA implementation: all AA's have to be initialized at runtime, even AA literals. In my prospective AA replacement, I've worked out a way to create compile-time AA literals via CTFE and mixins, though I haven't actually implemented it yet. Preliminary testing code seems to show that this should be quite possible.
 // ok
 string[int] aa2;
 static this()
 {
     aa2 = [1: "a"];
 }

Yes, this is the workaround currently necessary.
 // The same with shared fails
 // segfault
 /+
 shared string[int] aa3;
 shared static this()
 {
     aa3 = [1: "a"];
 }
 +/

Now this I've no idea about. But I know there are some bugs with shared currently; you might want to search the bugtracker for issues that might be causing this. T -- He who sacrifices functionality for ease of use, loses both and deserves neither. -- Slashdotter
Mar 18 2012