const method and return type
Andrea Fontana
nospam at example.com
Fri Dec 13 16:53:25 PST 2013
On Saturday, 14 December 2013 at 00:31:24 UTC, Adam D. Ruppe
wrote:
> On Saturday, 14 December 2013 at 00:24:01 UTC, Andrea Fontana
> wrote:
>> Just another thought. If we have:
>>
>> class B;
>> struct C;
>>
>> class A
>> {
>> void method() const { ... }
>> B another_class;
>> C a_struct;
>> }
>>
>> B is just a reference to a object, so method() should not
>> reassign it. The reference should be const, not the object
>> itself. method() should be able to call mutable another_class
>> methods. Am I wrong?
>
> Yes, in D, all members of a const object are const too. So
> inside method() const, another_class is const. Which means
> another_class.member is also const.
Why? The object itself it's not a member. The reference to that
object is the member.
Consider this:
class A {}
class B
{
A first;
A second;
}
void main()
{
auto a = new A;
auto b = new B;
b.first = a;
b.second = a;
assert(b.first == b.second);
assert(&b.first == &b.second);
}
Second assert fail, of course.
"first" and "second" are just two reference. They are different
reference to the same object.
Those reference should be const, not the object they refer.
Consider this way to escape current constness:
class A { int x; }
A globalA;
class B
{
void method() const
{
// first.x = 10; This doesn't work. But IMO it should
globalA.x = 10; // This work. Same effect as preceding
line
writeln(first.x); // 10!
}
A first;
A second;
}
void main()
{
globalA = new A;
auto b = new B;
b.first = globalA;
b.second = globalA;
b.method();
}
You see?
More information about the Digitalmars-d-learn
mailing list