Thread overview | |||||
---|---|---|---|---|---|
|
March 21, 2010 Returning this from a const member | ||||
---|---|---|---|---|
| ||||
According to http://digitalmars.com/d/2.0/const3.html: ---- Const member functions are functions that are not allowed to change any part of the object through the member function's this reference. ---- With the following code: ---- class Foo { Foo myFoo() const { return this; } } void main() { auto f = new Foo; } ---- I get the error: ---- test.d(5): Error: cannot implicitly convert expression (this) of type const(Foo) to test.Foo ---- Why is this? myFoo() isn't changing any part of Foo, so it should be fine according to the spec... Or is const like immutable here where it causes the rest of the object to become const if one member function is? If it is then maybe the spec should be updated to clarify this? |
March 21, 2010 Re: Returning this from a const member | ||||
---|---|---|---|---|
| ||||
Posted in reply to Robert Clipsham | Robert Clipsham:
> Why is this?
It's not a hard question. This code compiles:
class Foo {
const(Foo) myFoo() const {
return this;
}
}
void main() {
auto f = new Foo;
}
It's just in a const function the "this" is const, so if you want to return it, then you have to use a "const Foo" type, because it's not a mutable Foo :-)
Bye,
bearophile
|
March 21, 2010 Re: Returning this from a const member | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile | On 21/03/10 00:18, bearophile wrote:
> Robert Clipsham:
>> Why is this?
>
> It's not a hard question. This code compiles:
>
> class Foo {
> const(Foo) myFoo() const {
> return this;
> }
> }
> void main() {
> auto f = new Foo;
> }
>
> It's just in a const function the "this" is const, so if you want to return it, then you have to use a "const Foo" type, because it's not a mutable Foo :-)
>
> Bye,
> bearophile
Now you say it, that does seem obvious, thank you :)
|
Copyright © 1999-2021 by the D Language Foundation