What is the best way to deal with this?
Steven Schveighoffer
schveiguy at yahoo.com
Sat Feb 23 19:57:38 PST 2013
On Sat, 23 Feb 2013 22:33:29 -0500, Martin <martinbbjerregaard at gmail.com>
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
More information about the Digitalmars-d
mailing list