On Sat, 23 Feb 2013 22:33:29 -0500, Martin <[email protected]> wrote:

        import std.stdio;

        class TestClass(T)
        {
        private:
                __gshared TestClass[] globalInstances;
        public:
                this()
                {
                        globalInstances ~= this;
                }
                
                void test()
                {
writeln("Address of variable globalInstances is: 0x", globalInstances.ptr);
                }
                
        }

        void main(string[] args)
        {
        
                TestClass!(int) t1 = new TestClass!(int);
                TestClass!(string) t2 = new TestClass!(string);
                
                t1.test;
                t2.test;
                
                readln;

        }

Outputs:
Address of variable globalInstances is: 0x4F3F80
Address of variable globalInstances is: 0x4F3F60

Which I guess makes sense since there's seperate globalInstances variables generated per template instance of the class. I want to store ALL instances, no matter if it's a TestClass!(int) or TestClass!(string) though.

Should I just use a __gshared void*[] globalInstances outside of the template and cast when necessary or is there an easier way that I'm too stupid to see? It's really late here...

You could create a base class for all:

class TestBase
{
private: // or protected?
   __gshared TestBase[] globalInstances;
... // same as what you have
}

class TestClass(T) : TestBase
{
   ...
}

Now, I have 2 points to make besides this.

1. The runtime is not especially equipped to deal with __gshared appending from multiple threads. Remember that __gshared is not a type constructor, so the runtime thinks this is a THREAD LOCAL array. Tread very cautiously with this kind of code. 2. Note that globalInstances is going to keep all your instances in memory, even if nothing else is referencing it. It's surprisingly difficult to avoid this problem. As I'm sure this is demonstration code and not your real code, I don't know your application enough to know if this is a problem.

-Steve

Reply via email to