pointers, functions, and uniform call syntax
monarch_dodra
monarchdodra at gmail.com
Tue Sep 4 03:44:12 PDT 2012
On Monday, 3 September 2012 at 21:18:28 UTC, Carl Sturtivant
wrote:
> On Monday, 3 September 2012 at 12:12:46 UTC, monarch_dodra
> wrote:
>> [SNIP]
>
> In a nutshell, I think you're broadly saying that you want to
> program with a struct S the same way whether it's stack or heap
> allocated. (Good code reuse, and no duplication of semantics
> with -> as in C++.) From this perspective the trouble is that
> "S()" and "new S()" don't have the same effect except for
> allocating one on the stack and one on the heap, and the
> language forbids you from overcoming this via reference
> variables, except by calling a function and passing "*r" to a
> "ref S" parameter.
>
> [SNIP]
Yeah, in a nut shell, that is pretty much it. There are several
ways to "work around it", but, IMO, none are good enough:
*Function with ref: Too intrusive, especially for more
complicated functions.
*Structs that implicitly alias This (such as RefCounted): Ref
Counted itself I'm not a huge fan of, since I don't see why I'd
pay for RAII when I have a GC. As for the rest, it is not in the
library, so I wouldn't want to roll one out myself.
**Furthermore, these wrapper structs have a way of "tainting" the
type system: When you pass your struct to a template, the
template will instantiate on your struct itself, and not on the
wrapped type.
*structs with explicit dereference (those that have "get", for
instance): That's just trading "*" for "get".
For now, I'll just (*s) it. It isn't broken or anything...
----
What I regret though, is that since D is Garbage Collected, it is
just screaming to be able to write:
----
S& val = *(new S);
val.doSomthing();
doSomething(s);
...
----
This is legal in C++, but it leaks* :/ D should be able to
harness such expressiveness with no problems whatsoever though.
*Actually, I've done this in C++ for classes that have hefty
attributes that need to be allocated, but otherwise don't need
pointer functionalities. You just have to make sure to correctly
implement the CC to avoid aliasing, and to "delete &val;" in the
destructor. Once you've done this though, then for all intents
and purposes, "val" is a value attribute. Nifty.
More information about the Digitalmars-d
mailing list