Having trouble with objects.

Jarrod qwerty at ytre.wq
Tue Mar 18 16:12:49 PDT 2008


On Tue, 18 Mar 2008 09:05:19 -0400, Jarrett Billingsley wrote:

> NRVO (Named Return Value Optimization) to the rescue.  There are no
> struct constructors, but it doesn't mean the compiler can't optimize
> this out. When you return a struct from a function, chances are very
> good that it will not be pushed onto the stack, but will be constructed
> in place.  So even though it looks like you're allocating (on the stack)
> and filling out a struct in the function, the compiler will rewrite the
> function so that a pointer to the struct is passed as a parameter and
> the function fills out the struct in place.

This is good to hear. I guess I won't feel (as) guilty about having to 
pass back a struct then.


> Well, what would you have to do in C++?  So you have multiple implicit
> cast overloads, but how is the node represented?  As a tagged union?  As
> a string which is converted to the correct type upon use?  Is there a
> member in the node which represents its type?  Don't you still need to
> check that the node is of the correct type before getting its value
> anyway, by which time you already know the type and the implicit cast is
> next to useless?
> 
> It sounds like your node is wanting to be a variant.  In D1, there's a
> variant type in std.boxer called Box, and in D2, there's std.variant. 
> (In Tango, there's tango.core.Variant.)  Or, if you want to implement it
> yourself, it's not that hard, it's basically a tagged union with some
> methods to check the type and convert it to a desired value.

Well yeah the node acts much like a variant. And yes, it internally uses 
a union with an enum to keep track of the stored value type. 
It tries its best to convert the stored value to the desired type upon 
being called. My problem isn't with storing or handling the abstract 
data, it's that I need to use an overloaded function call to get the 
value. It's quite ugly and results in a lot of temporary variables being 
created when they don't need to be created, like for instance if I wanted 
to pass a number to a function:
>int temp;
>myNode.getValue(temp);
>someFunc(temp);

In C++ with overloaded return types I can just use:
>someFunc(myNode); //Sometimes a cast is needed, but it's still better

Okay, it's not exactly a show stopper, it's just a bit ugly and somewhat 
inconvenient.
With that said, it looks like boxer/variant have workarounds for this 
using templates. I'll look at their source and see how it's done. 

Thanks for your reply, it was quite helpful.


More information about the Digitalmars-d-learn mailing list