March 19, 2008
Writing that code without "ref" in "add" and "get" didn't work well the first time. I got array index out of bounds. Aren't dynamic arrays always passed by reference?

Ary Borenszweig escribió:
> It seems TList is just a list of anything. In that case, you can use this code:
> 
> ---
> import std.stdio;
> 
> // Starts definition of TList
> alias void*[] TList;
> 
> void add(T)(ref TList list, T elem) {
>     list ~= cast(void*) elem;
> }
> 
> void* get(ref TList list, int index) {
>     return list[index];
> }
> // Ends definition of TList
> 
> class Foo {
> }
> 
> class Bar {
> }
> 
> void main()
> {
>     TList list;
>     list.add(new Foo());
>     list.add(new Bar());
>     list.add(3);
> 
>     Foo foo = cast(Foo) list.get(0);
>     writefln("At 0: %s", foo.stringof);
> 
>     Bar bar = cast(Bar) list.get(1);
>     writefln("At 1: %s", bar.stringof);
> 
>     int val = cast(int) list.get(2);
>     writefln("At 2: %s", val);
> 
>     writefln("Length: %s", list.length);
> }
> ---
> 
> However, if you need a list of a specific type, you can use dynamic arrays: http://digitalmars.com/d/1.0/arrays.html
> 
> lurker wrote:
>> the best i can do is to offer a link. one will better understand that then my english:
>>
>> http://www.functionx.com/bcb/classes/tlist.htm
>>
>> thanks
>>
>>
>> Jarrett Billingsley Wrote:
>>
>>> "lurker" <lurker@lurker.com> wrote in message news:frmfko$1rg6$1@digitalmars.com...
>>>> hi all,
>>>> with borland c++ one does have with the VCL the TList.
>>>> is there anything like TList in D that one can use instead?
>>>>
>>>> thanks
>>> For those of us who have never used Borland C++, could you explain what a TList is/does?
>>>
>>
March 19, 2008
"Ary Borenszweig" <ary@esperanto.org.ar> wrote in message news:frqsik$1ngj$1@digitalmars.com...
> Writing that code without "ref" in "add" and "get" didn't work well the first time. I got array index out of bounds. Aren't dynamic arrays always passed by reference?

Yes, but the reference isn't passed by reference ;)

It's the same as something like:

void foo(char* s)
{
    ...
    s = realloc(s, 20);
}

Now s points to a new place in memory.  Yes, the contents pointed to by s were passed by reference, but the caller doesn't see the update to s.

In the same way:

void foo(char[] s)
{
    ...
    s ~= "hi!";
}

The local variable 's' is updated in the function, but the caller may not see those changes.


1 2
Next ›   Last »