Best practices for class instance variables as parameters
Andy Valencia
dont at spam.me
Sat Sep 28 18:31:24 UTC 2024
On Saturday, 28 September 2024 at 18:16:55 UTC, Ian wrote:
> Hi,
>
> I'm coming from C and some C++ so the way D stores class
> instance variables is new to me. If I'm not mistaken the basic
> unadorned instance variable is like a "hidden" pointer. So,
> when passing class instance variables to a function, what would
> be the point of passing a pointer or ref?
An instance of a class is, of course, an object. The instance's
variables can be int's or float's or struct's. Values. The
instance has storage right there to hold the value.
An instance can also reference another class instance. Then,
underneath, that's a pointer.
> I think I answered myself, in that they'd would be pointers or
> references to the variable that holds the... hidden pointer to
> the class instance.
I think I see you assuming that how an instance variable treats
values is different from how a local variable or a struct field
would treat a value. My experience is they're all the same. The
important difference between struct and class instance is that
structs want to be values, and you have to go to extra trouble to
work with pointers thereof. Instances want to be references, and
you have to go to trouble (shallow or deep copy, presumably) if
you want to get a value copy. But all this applies equally to
instance variables and a struct's fields.
> Now I'm unsure. When I pass a class instance to a function by
> value, I'm not creating a copy of the instance, am I?
No you aren't.
(Now let the much deeper Dlang minds sweep in and correct me.)
More information about the Digitalmars-d-learn
mailing list