Why are structs and classes so different?
Mike Parker
aldacron at gmail.com
Sun May 15 20:39:07 UTC 2022
On Sunday, 15 May 2022 at 20:05:05 UTC, Kevin Bailey wrote:
>
> One question is, how should we pass objects - by value or by
> reference? In C++, you can do either, of course, but you take
> your chances if you pass by value - both in safety AND
> PERFORMANCE. The bottom line is that no one passes by value,
> even for PODs (although we may return even large objects.)
Pass struct instances by ref or by value as needed, just as you
do in C++.
For classes, you never have direct access to the instance. Your
class reference is a handle (a pointer) that is always passed by
value.
>
> But I asked a different question: Why can't I put a class
> object on the stack? What's the danger?
I answered that one. You can put a class on the stack with
`scope`. There is no danger in that.
If you're wanting direct access to the class instance, like you
would have with a struct, you don't have that in D. Classes are
modeled on Java, not C++.
>
> Note that operating on that object hasn't changed. If I pass by
> reference, it's no different than if I had created a reference.
Again, you never have direct access to the object instance. You
always access it through the handle.
>
> One might say, Well, if D creates by value, then it has to pass
> by value. But it doesn't; it has the 'ref' keyword.
Everything is passed by value unless the `ref` keyword is present.
>
> One might want to avoid passing by value accidentally. Ok, one
> could have D pass class objects by reference implicitly.
How do you pass by value accidentally? By forgetting the `ref`
keyword?
>
> I don't like things silently changing like that, so one might
> have D forbid all but pass by 'ref' or pointer for class
> objects.
I don't understand where you're coming from here. How can things
silently change?
>
> I hope Ali's answer isn't the real reason. I would be sad if D
> risked seg faults just to make class behavior "consistent".
>
Where is the risk of seg faults? Are you referring to the fact
that class references are default initialized to null?
More information about the Digitalmars-d-learn
mailing list