property returning a reference vs returning a value
Jonathan M Davis
jmdavisProg at gmx.com
Tue Jun 19 23:33:36 PDT 2012
On Wednesday, June 20, 2012 05:42:25 cal wrote:
> This doesn't compile, because the assignment matches both
> property functions in S:
>
> struct S
> {
> @property int a() { return _a; }
> @property ref int a() { return _a; }
> int _a;
> }
>
> int main()
> {
> S s;
> s.a = 5;
> }
>
> But I would like to be able to do different things when I pass
> out a reference to _a compared to when I just pass out the value.
> I also don't want to require an argument to the ref property
> function. Is there a way to do this?
You can't overload on return type. The parameters need to be different, or the
functions are going to conflict. The fact that you're dealing with a property
is irrelevant (other than the fact that that means that you can't actually
have differing parameters save for the this parameter by making the function
mutable, const, immutable, or shared). So no, you can't have two of the same
property where one returns ref and one doesn't.
But properties which return ref are generally pretty pointless anyway (unless
it's const ref). As soon as you return non-const ref, the getter is also a
setter, and you have no control over the setting, because it happens via the
ref rather than a function. You might as well just use a public member
variable.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list