On 2015-06-26 22:45, Parke via Digitalmars-d wrote:
Hi,

I have a question about Walter's DConf keynote and the Memory
DisAllocation pattern.

http://dconf.org/2015/talks/bright.html

The following example is from the slides of Walter's talk.

----

auto toString(uint u) {
   static struct Result {
     this(uint u) {
       idx = buf.length;
       do {
         buf[--idx] = (u % 10) + '0';
         u /= 10;
       } while (u);
     }
     @property bool empty() { return idx == buf.length; }
     @property char front() { return buf[idx]; }
     void popFront() { ++idx; }
     char[uint.sizeof * 3] buf;
     size_t idx;
   }
   return Result(u);
}

import std.stdio;

void main() { writeln(toString(28)); }

----

My question is:

Does use of this pattern in D require that the size of the Result
struct be known by the compiler at compile time?

Or, perhaps more precisely:  Does the caller of toString need to know
the size of the struct that toString will return?

In the above example, buf's length is uint.sizeof * 3.  But what if
buf's length was a function of u (and therefore only known at
run-time), rather than a function of uint.sizeof?

Thanks!

-Parke


What you're asking for is probably type inference. Notice the auto return type? This keyword is actually very advanced and bleeding edge in natively compiled languages.

Internally, when the function is processed by the compiler, all types are evaluated before the instructions are even looked at, and the final size of all types are compiled and automatically put in place.

Afterwards, the instructions must obey consistency, ie. the caller can't use anything but auto or ReturnType!toString to accept an auto type because there's no way you can guess the mangling/size/etc otherwise.

This also means you can choose a ridiculous name or you can change the size of a stack allocated object any time without breaking an interface.

e.g. you could change this without breaking the API to something like:

auto toString(T)(T u) if (isNumeric!T) {
   static struct GenericResult {
     this(T u) {
       ...
    char[T.sizeof * 3] buf;
    ...
}

Reply via email to