Initializing assoc array to non-null
Greetings Is there a way to initialize an associative array to a non-null (but still empty) state? The only way I know is by adding an element and then removing it. Did I miss something obvious? Basically I want to write lines 7-8 in the following code in a cleaner fashion. Any ideas? Regards - Puneet class Foo { // 1 string[int] _aa; // 2 public string[int] aa() { // 3 return _aa; // 4 } // 5 this() { // 6 _aa[0] = "";// 7 _aa.remove(0); // 8 } // 9 } // 10 void main() { // 11 Foo foo = new Foo;// 12 string[int] bb = foo.aa; // 13 assert(bb !is null); // 14 bb[0] = "zero"; // 15 assert(bb is foo.aa); // 16 } // 17
Re: Initializing assoc array to non-null
Thanks Jonathan Do you think this could make a good enhancement request? Regards - Puneet On Sat, Jun 1, 2013 at 9:34 PM, Jonathan M Davis wrote: > On Saturday, June 01, 2013 20:21:42 d coder wrote: > > Greetings > > > > Is there a way to initialize an associative array to a non-null (but > still > > empty) state? The only way I know is by adding an element and then > removing > > it. Did I miss something obvious? Basically I want to write lines 7-8 in > > the following code in a cleaner fashion. Any ideas? > > Unfortunately, at the moment, I believe that that's the best that you can > do - > though it's trivial enough to write a function that does that for you so > that > you can make it a one-liner: > > auto aa = initAA!(string[int])(); > > or > > initAA(aa); > > - Jonathan M Davis >
class destructors and sub-objects
Greetings I have a question on class destructor method. D documentation for destructors says: "The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreference objects is not specified. This means that when the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects." Now I have a class A and it refers to subobject B. But B may or may not have other objects referring to it. As a result, an object of A is GCed, but subobject B may or may not be getting garbage collected. In this scenario, am I allowed to make a reference to subobject B from the destructor of A? Is there a way to find out if B is garbage collected or not? Regards - Puneet
Facing problems with Class Properties
Greetings All I am trying to compile the following D2 code. The code giving compilation issues is the "this()" function of the class Foo. The constructor basically tries to initialize all the data members of the class, of type BaseClass and of type BaseClass array. I am using class property tupleof to iterate over members of the class. Then I check the type of each member and if the member is a BaseClass array, I new all the elements of the array. Otherwise if the member is of the type BaseClass, I new it as it is. The issue is that when I try to compile the program, I get the error bug.d(10): Error: no property 'length' for type 'test.Bar' I am explicitly checking the field type, and I am making sure that the field is an array type, before looking for its length. So I am not sure why this error appears. Please guide me. Regards Cherry import std.stdio; class BaseClass { } class Bar: BaseClass { } class Foo: BaseClass { this() { foreach(i, f; this.tupleof) { if (is (typeof(f) : BaseClass[])) { for (size_t j = 0; j < f.length; ++j) { f[j] = new typeof(f[j]) (); } } if (is(typeof(f) : BaseClass)) { f = new typeof(f) (); } } } Bar instance1; Bar instance2; Bar [10] instances; } unittest { Foo foo; foo = new Foo; }
Re: Facing problems with Class Properties
> if(false) { > for (size_t j = 0; j < f.length...) > ... > } > > Semantically this code is wrong as you can't take the length of f which is > class Bar. The static if forces the compiler to not generate this code as it > is known to be false. > Thanks Jesse What you are saying makes sense to me. The problem is that the following code works perfectly. I have just commented out some part and replaced it with some debug statements. The output from this code makes me believe that "is" and "typeof" do have some run-time semantics. Or is it a D2 bug. BTW I am using Digital Mars D Compiler v2.050. Regards - Puneet import std.stdio; class BaseClass { } class Bar: BaseClass { } class Foo: BaseClass { this() { foreach(i, f; this.tupleof) { if (is (typeof(this.tupleof[i]) : BaseClass[])) { writeln("Creating new objects for all ARRAY types ", this.tupleof[i].stringof); // for (size_t j = 0; j < this.tupleof[i].length; ++j) { // this.tupleof[i][j] = new typeof(this.tupleof[i][j]) (); // } } if (is(typeof(this.tupleof[i]) : BaseClass)) { writeln("Creating new objects for all NON-ARRAY types ", this.tupleof[i].stringof); // this.tupleof[i] = new typeof(this.tupleof[i]) (); } } } Bar instance1; Bar instance2; Bar [10] instances; } unittest { Foo foo; foo = new Foo; } // I am getting the following output // Creating new objects for all NON-ARRAY types this.instance1 // Creating new objects for all NON-ARRAY types this.instance2 // Creating new objects for all ARRAY types this.instances
Re: Facing problems with Class Properties
> Is there a reason you can't directly reference the members? After all, you > are writing the class. > Thanks Steve for your inputs. Actually this is part of a bigger code that I am trying to create. Though I am pretty new to D. What I have posted is a reduced code that illustrated the issue I am facing. In the actual code, I am using string mixins and there are too many classes (all derived from BaseClass) and too many class instances, and the constructor call for Bar (and other classes) is a bit more involved. There is a need to make sure that all the constructors are called in a seamless fashion. In fact, I will not be the end-user. I would just be coding the BaseClass and the mixin. The actual end-users are not supposed to be quite D-literate and I would be asking them to code something to the effect: class Foo: BaseClass { mixin(CreateInstances()); // Define your Bar and other sub-class instances here //... // More code here } Any ideas? Regards - Cherry
Re: Facing problems with Class Properties
> What you are saying makes sense to me. The problem is that the > following code works perfectly. I have just commented out some part > and replaced it with some debug statements. Ah.. Now I think I understand. This new code I have written will all be run at compile time. So in this case, the foreach statement inside the constructor would be reduced to a bunch of writeln statements at compile time and those writeln would be executed at the run time. This will not happen with the actual code since there are other typeof and is statements in there that can not be run at runtime. Did I get it right?
Re: Facing problems with Class Properties
> Another thing, is(T : U) simply means T is implicitly castable to U. Due to > a compiler bug, Bar[] is implicitly castable to BaseClass[]. > Steve I realize that I am using this compiler bug as a feature. It would be kind of you to suggest me a code that would not exploit this bug. I was thinking of using something to the effect: if (__traits(isStaticArray, this.tupleof[i]) { if (is (typeof(this.tupleof[i][0]) : BaseModule)) { Regards - Cherry
Re: Facing problems with Class Properties
> Ah.. Now I think I understand. > > This new code I have written will all be run at compile time. So in > this case, the foreach statement inside the constructor would be > reduced to a bunch of writeln statements at compile time and those > writeln would be executed at the run time. This will not happen with > the actual code since there are other typeof and is statements in > there that can not be run at runtime. > > Did I get it right? > If I got it right now, It will be possible for me to unroll the foreach loop and the if statements in a mixin and that would work well. Or may be changing the "if" statement to "static if" would do the trick. I will give it a try. Thank you Steve and tank you Jesse for showing me the light. Regards - Cherry
List of derived types?
Greetings I need a way to know (using traits or other compile time constructs) all the types derived from a given type. Is it possible in D? Is it possible to get a list of all the user-defined classes? I could use that to filter out the classes that I need. Regards Cherry
Re: List of derived types?
> I'm curious, why do you need that? > It is a long story. But basically I am creating a platform wherein the users would be deriving classes from some base classes that I write as part of the platform. And the users would often be deriving many such classes. The end-users would often not be programmers and would know little D (as you can see I am also learning D :-). I want to automate some code generation for them and I hope to do that by creating wrapper classes that would shadow the classes that the end-users have written. Since the and users would be instantiating these classes only inside a particular class scope, I wanted to create some code inside that class scope. Right now I am forcing the end-users to insert some mixin for every class that they code. I wanted to automate that process. Hope what I said makes sense to you. Regards Cherry Hope what I said makes sense.
is expression for template structs/classes instances?
Greetings I want to find if a given struct type is instantiated from a particular template struct type. For example: struct S (T) { alias T Type; T t; } And later I want to find out if a given type is of type S(*) (basically any type instantiated from template struct S). In fact I do not know the type value T used at the time of instantiating S!(T). I was looking at "is ( Type Identifier : TypeSpecialization , TemplateParameterList )" expression at http://www.digitalmars.com/d/2.0/expression.html#IsExpression . Thought there would be some way using that, but I could not find any. Regards Cherry
Re: is expression for template structs/classes instances?
> For instance, given your definiton of S, you could use > _traits/std.traits to check that the type that you're testing has a member > variable t. You could then check that S!(typeof(t)) was the same as the type > that you were testing. So, if you get particularly cunning about it, I believe > that it can be tested for in specific cases, but I don't believe that it can > be > done in any general way. > Thanks Jonathan That is exactly what I had thought of doing. I was conscious that it may not be the cleanest way. Now that you are saying a cleaner way may not exist, I will go ahead and write the code. Regards - Cherry
Re: is expression for template structs/classes instances?
> S!int foo; > static if ( is( typeof(foo) f == S!T, T ) ) { > // Here, T == int, f == typeof(foo) > } > > Note that the syntax "is ( Type Identifier : TypeSpecialization , > TemplateParameterList )" is only usable inside static if. > Thanks Simen I do know the template. I will try out your solution. Will let you know if I face issues. Regards - Cherry
Re: is expression for template structs/classes instances?
> I do know the template. I will try out your solution. Will let you > know if I face issues. > Simen It works perfect, And this is exactly what I was looking for. If you see my original post, I also thought this form of "is" expression should work. Just could not get around to the right syntax. With your help it is working now. I am using a slightly more elaborate check which is obvious but I am writing it here to just let the list know. static if ( is( typeof(foo) f == S!T, T : int) ) { // foo is an object of type S!T // where T is convertible to int } Thanks once more Warm Regards - Cherry
Nested Structs
Greetings All I have a situation where I have a struct nested inside a class. I would like to make the enclosing class' members visible inside the nested struct's constructor. I see that such preposition is feasible for nested classes, but not for nested structs. Why so? Are there some alternative constructs which could give me this behavior for nested constructs? Regards - Cherry
Re: Nested Structs
> A struct nested in a class does not have a hidden "outer" pointer as a > nested class does. It's because a struct is generally more bare-bones than > a class (which has loads of hidden pieces: vtable, interfaces, classinfo, > etc.). Also, instantiating such a struct does not tie it to a class > instance. > Thanks Steve As far as I am concerned, this is a very limiting behavior wrt structs nested inside classes. I have also observed that if you define a constant (using enum for example) inside the enclosing class, the constant remains visible in the nested struct too. So I believe the language is making the hidden "outer" scope visible to the nested struct (or maybe there is some other mechanism for enums that I am not aware of). > You need to implement this behavior on your own: > Actually I am trying to define a DSEL and the end users are not typically programmers. I am in a situation where the end-user decides the unit in an enclosing class (unit of length as an inch for example) and later whenever he instantiates a line or a shape, the particular unit is automatically considered at the time of instantiation. For my application, I need value semantics and therefor using nested classes in place of structs can not be considered. Making the end-users pass the unit or its context (in form of this pointer) everytime they instantiate a shape would be atrocious. It would defeat the very purpose of letting the end-user define a unit. I know I am not on the right mailing group, but I want to ask for this particular language enhancement. I believe this would make the behavior of the language more straight wrt nested structs inside classes (are not these beasts expected to serve like nested classes or even structs nested inside function scopes?). I hope my requirement is generic enough and fits the bill for an enhancement request. Regards - Cherry
Maximum Number of Threads?
Greetings Is there a limit on the maximum number of threads that can be spawned? Or does it just depend on the value in /proc/sys/kernel/threads-max on a linux system? Regards - Cherry
Dynamic and Static Casting
Greetings All I have learnt that D has only one casting operator and that is 'cast'. The same operator assumes different functionality depending on the context in which it he being used. Now I have a situation where I have to downcast an object and I am sure of the objects type and thereby I am sure that the downcast would only be successful. To make the operation faster, in C++ I could have used static_cast operator, thus giving the RTTI a skip. Would this be possible in D? Can I force a static_cast which downcasting? Regards - Cherry
Re: Dynamic and Static Casting
Thanks Lars and Bearophile, I will give it a try. I understand that static downcasting is dangerous. But there are places where efficiency is paramount and you are sure that the casting is safe. So I wholeheartedly second your proposal to have the stuff in phobos. Regards - Cherry
Number of references to a Class Object
Greetings I am in a situation where I need to know the number of references to a class' object. To explain, I have an array of class objects and I occasionally process this array. But if a particular object in this array is not being garbage collected just because it is part of this array, I would like to loose that object by making it null. So either I need to find out the number of references to that object and in case there is only one reference, I force the object null. If this is not possible, I am sure there would be alternative solutions since this should be a common situation faced by programmers. Please help. Regards - Cherry
Re: Number of references to a Class Object
> I believe what you're referring to is generally called a Weak > Reference, which is a reference that the GC doesn't consider when > deciding to keep an object alive, but that the GC will update if an > object dies. > There's a feature request at > http://d.puremagic.com/issues/show_bug.cgi?id=4151 > Thanks Andrew Is there a way fro the users like myself to vote up an issue on DMD Bugzilla. Regards - Cherry
Re: Number of references to a Class Object
> Also tango (for D 1.0) implements it. > Link: > http://www.dsource.org/projects/tango/docs/current/tango.core.WeakRef.html > > Might be worth a look if you are going to implement it for D 2.0. > I looked at the D1 implementation. It depends on GC methods weakPointerCreate and weakPointerDestroy. These functions are implemented in D1 GC as extern C functions. It seems most of this code should be directly portable to D2, it would certainly require changes in the DMD2 source code. I have never worked at that level and have used D2 only for past couple of months. While I can give that a blind try, it would be useful only if it gets excepted in DMD2. What do you guys suggest? Regards - Cherry
Re: Number of references to a Class Object
> If you know roughly what to do and want to take a stab at producing a viable > patch to fix the problem, then feel free. If it's solid, it may get in. I > don't > know. It doesn't hurt to try though (as long as you're prepared for the fact > that it may not be accepted). Thanks for letting me know of the licensing issues. I do not think I have the expertize required to fix this myself. So I hang my shoes here and wait for somebody else to get stuck in a similar situation. Regards - Cherry
Re: Number of references to a Class Object
> However, it's not generally an issue, because you shouldn't normally be > keeping > references around for stuff that isn't used anymore. The garbage collector is > smart enough to deal with circular references and the like, so the biggest > cases > where you'd normally need weak references aren't actually a problem. You're > trying to do something fairly abnormal here. > Thanks Jonathon, with some effort I hope to wriggle out of the situation. Regards - Cherry
Error: this for ~this needs to be type foo not type foo[1u][1u]
Greetings I am getting this error when I am instantiating a struct array with a single element inside another class and only if there is the destructor for the struct is explicitly defined. Is it a known error? Here is a minimized snippet that gives error: $ rdmd --main -unittest test.d Error: this for ~this needs to be type foo not type foo[1u][1u] Error: this for ~this needs to be type foo not type foo[1u] // test.d struct foo { int foofoo; ~this() { // no error if explicit destructor not // defined } } class bar { foo fred; foo[2][2] foofoo; foo[1] frop; // this gives error foo[1][1] fropfrop; // this too } unittest { foo frop; foo[1][1] fropfrop; // this works bar burp; }
Are function pointers compile time constants?
Greetings I tried to initialize a struct member with a function pointer, and found that DMD2 did not like it. Are not function pointers compile time constants? And why they should not be? Regards - Cherry
Re: Are function pointers compile time constants?
Thanks Simon.
Doubt about Synchronized Code Clocks
Greetings I have a doubt about synchronized code blocks. I learnt that in Java the synchronized keyword has two fold effect. Firstly it locks the code to make sure that only a single thread gets access to the code block at a given time. Secondly, it makes sure that the data elements accessed inside the code block are not "stale". As a result Java programming practice is to synchronize even access functions that access shared data elements. How about D? Does D synchronized keyword just result in mutex locking of the code block? Or does it also ensure that the accessed shared data elements are not stale? Thanks and Regards - Puneet
Re: Doubt about Synchronized Code Clocks
> I'm afraid that I have no idea what would be "stale" about a shared variable. > sychronized uses a mutex, and if you want to avoid race conditions, you need to > use mutexes or something similar when dealing with shared variables. But I don't > know what would be "stale" about a variable. > One thread modifies a shared variable and the other thread still gets an old value. I do not know if this is applicable to D at all. Just wanted to get a clarification after I read an article in "Java Concurrency in Practice" book. I quote a relevant paragraph: Locking is not just about mutual exclusion; it is also about memory > visibility. To ensure that all threads see the most up-to-date values of > shared mutable variables, the reading and writing must synchronize on a > common lock. Regards
Why is it necessary to use synchronized functions when passing shared variables?
Greetings Why is it necessary to use synchronized functions when passing shared variables? I get error even when I am not modifying the shared variable in the function. Kindly look at the following code. I get a compile error unless I declare the functions parent and root synchronized. The compile error says: test.d(13): Error: function test.HierObject.root () const is not callable using argument types () shared const Thanks and Regards - Puneet // Reduced Code import std.exception; // synchronized // Compiles without error when uncommented class HierObject { private shared HierObject _root; private shared HierObject _parent; shared(const(HierObject)) root() const { if(_root) return _root; else { enforce(_parent, "HierObject Instance does not have a parent!"); return this.parent().root(); } } shared(const(HierObject)) parent() const { enforce(_parent); return _parent; } }
Re: Why is it necessary to use synchronized functions when passing shared variables?
> > > It's probably complaining because using shared without synchronizing is > generally very foolish. Now, I would have _thought_ that it would still > work > without, but I apparently not. Regardless, I'm not sure why you'd want to > use > shared anything without synchronizing your access of it. Thanks Jonathan Actually in my actual use case, I am using synchronized at code block level -- to limit the scope of locking. I am doing this to mitigate possible inefficiency due to indiscriminate use of mutex locked code. But D is forcing me to synchronize at function level, thus making most of my code go under mutex locks. Regards - Puneet
Do I need to declare instances of Mutexes, Semaphores, and Barriers shared?
Greetings Do I need to declare instances of Semaphores, Mutexes and Barriers shared? In most situations these objects would be naturally accessed by many threads. Regards - Puneet
Why is the struct instance being copied here?
Greetings Please look at the code down here. When compiled and run, I get the message "Call to postblit" printed. I think it is because of the foreach block, because the variable "i" is not declared as ref there. Is there a way to make it a ref? Regards - Puneet import std.stdio; struct Foo { this(this) { writeln("Call to postblit"); } } class Bar { Foo foo; this() { foreach(i, f; this.tupleof) { // do nothing } } } void main() { Bar bar = new Bar(); }
Next Release
Greetings All It has been 2 months since we had release 2.052. Just wondering when is the 2.053 release planned? Also, is there an automated way to create a snapshot release from the git repositories? Regards - Puneet
Unable to pass shared class method as delegate
Greetings I am facing problem passing a shared class method as an argument to a function. Look at the following minimized code snippet. class Foo { shared // compiles when commented out void bar() {} } void frop(void delegate() dg) { } void main() { shared Foo foo = new shared(Foo); frop(&foo.bar); } I get the following errors (using dmd 2.052) dg.d(11): Error: function dg.frop (void delegate() dg) is not callable using argument types (void delegate() shared) dg.d(11): Error: cannot implicitly convert expression (&foo.bar) of type void delegate() shared to void delegate() Please suggest a valid signature for the function frop, so that it can take shared delegates. Regards - Puneet
Re: Unable to pass shared class method as delegate
> > > I've copy and pasted my reply to Benjamin below, you should be able to > adapt it to your needs: > Stupid me. Should have checked the list before posting. > > The only way I've found to do this that works is using an alias - this is > probably worth a bug report if there isn't one already. I checked and found that this is already reported http://d.puremagic.com/issues/buglist.cgi?quicksearch=shared+delegate And since Walter says that const issues are high on his priority list, I hope this would get resolved soon. Regards - Puneet