Re: Overload resolution (value vs reference)
Thanks for explanation!
Overload resolution (value vs reference)
How does compiler selects the proper function among overloaded functions which differ only in the way the argument is passed (by reference or by value)? Is there a way, to control this behavior? Result of execution of the test code: passed by value: 8 passed by value: 3 passed by value: Foo(10) Test code: import std.stdio; struct Foo { int value; } void f(T)(T foo) { writeln(passed by value: , foo); } void f(T)(const ref T foo) { writeln(passed by reference: , foo); } void main() { // 8 is a r-vlaue, so it's passed by value f(8); // i is a l-value, it's passed by value and it's ok int i = 3; f(i); // foo is a l-value, it's passed by value again, but if structure will be big enough it'll be ineffective auto foo = Foo(); foo.value = 10; f(foo); }
Resizing array of classes
Suppose I have a dynamic array of classes, something like: class Foo { int value; } Foo[] a; Now I want to resize it and initialize new items with default values, so I do following: a.length = 10; a[0].value = 1; And by executing the last line of code I've got a segmentation fault. Apparently a.length = 10 resizes array and creates 10 references to Foo, but objects of Foo were not created. Do I need to manually iterate over new items of the array and explicitly call a[i] = new Foo, or there is a better (automatic) way?
Returning dynamic array from the function
I tryed to learn how arrays works and found another strange thing: import std.stdio; int[] create() { int[5] a1 = [ 10, 20, 30, 40, 50 ]; int[] b1 = a1; writeln(b1: , b1); return b1; } void main() { int[] a2 = create(); writeln(a2: , a2); } Result of execution: b1: [10, 20, 30, 40, 50] a2: [-142625792, 32767, 4358059, 0, 5] Please explain what's wrong with this code? Why variable a2 contains crap? Is this another dmd/druntime bug or I missed something?
Re: Returning dynamic array from the function
b1 points to the exact same data as does a1. This data is stack- allocated, and thus a2 points to an overwritten stack frame. Thanks for explanation, I thought contetns of a1 are copied to the heap when assignment operator executed.
Returning reference to integer from property setter function
Hi! How I can return from function a reference to int? Here is a simple code, to demonstrate my problem: struct Foo { public: @property int foo() const { return x_; } @property ref int foo(int value) { x_ = value; return x_; } private: int x_; } void main() { auto f = Foo; f.foo += 5; } When I try to build this code, I get the error at line f.foo += 5 with message: Error: f.foo() is not an lvalue. I thought the ref qualifier causes the compiler to return a reference in that case.
Re: Returning reference to integer from property setter function
Thanks for reply, hopefully this issue will be fixed sometime..