Boost logo

Boost :

From: Daryle Walker (darylew_at_[hidden])
Date: 2004-01-19 04:12:50


[Sorry that this is extremely late]

On 1/4/04 3:03 AM, "Thorsten Ottosen" <nesotto_at_[hidden]> wrote:

> "Dan W." <danw_at_[hidden]> wrote in message
> news:bt8glf$3lf$1_at_sea.gmane.org...
>>> The most important application of propagating constness is when storing an
>>> object by pointer in a class:
>>>
>>> class X
>>> {
>>> smart_ptr<My_polymorhic_type> p_;
>>> public:
>>> int bar() const
>>> {
>>> return p_->this_is_also_a_const_function(); // compile time error if not
>>> }
>>> };
>>
>> That's neither a const, nor a non-const function of p_, you're calling; it's
>> a function of what p points to.
>
> Please don't obscure the discussion by pointing out language details..

Actually, what you're dismissing as an obscure detail is the CORE point! A
pointer and the object which it (potentially) refers are different objects,
so the C++ creator(s) decided that their "const" states should be
independent.

>> That a function is const means that it doesn't change the class state, i.e.:
>> what _address_ the pointer points to. But the target at that address is _not_
>> part of the state of this class,
>
> You cannot make this statement and think it is a universal truth. To me it is
> part of the state. There is nothing to discuss. Some people like it one way,
> others don't. Both views should be respected.

But what you just said can't be an universal truth either! The compiler can
only support one opinion internally.

>> so why should the constness of a member function of _this_ class have to bear
>> responsibility for some class elsewhere, just because we have its pointer?
>
> because the state of the object depends recursively on what member (pointers
> or not) that the object owns.

But, from the perspective of the core language, how is the compiler supposed
to know if a pointer contained in a class owns the pointed-to object or not?
The compiler _can't_ know, so it has to pick the safer (and easier to
implement) current semantic of independent "const" states.

If you want a pointer whose "const" state matches that of the pointer-to
object, you can make you own smart pointer for it. Just like using an
"auto_ptr" as a class member to prevent forgetting of pointer-based
deletion, this new smart pointer will allow a pointed-to (owned) object to
have the same "const"-ness of the current member function, instead of having
no qualifications (and be changed if the programmer accidentally uses the
object in a non-const manner). Post it to Boost for inclusion when you're
done!

-- 
Daryle Walker
Mac, Internet, and Video Game Junkie
darylew AT hotmail DOT com

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk