Stepping back and looking at constness from another angle.
Ary Manzana
ary at esperanto.org.ar
Thu Jun 7 04:49:54 PDT 2007
Thanks for the examples, I liked them. Now I see where is the problem,
compared to other languages that doesn't have const, but have created
hacks to avoid it.
For example in Java, if a class has a List of something, and you want
to expose it in a way that doesn't allow the caller to add elements,
then you return an array of the elements. Of course, here the caller can
still modify each of the elements in the array, but at least one problem
is avoided. I guess creating an array is fast in Java, but it's sure
faster not creating it and enforcing the caller not to modify the
elements. And still the problem of being able to modify the elements exists.
Which makes me think... Will const, final, invariant be used in method
declarations to say "Calling this method this class won't be modified"?
(the const after the function declaration, right?) I've been sort of
following the threads and I haven't seen anything mentioning this.
eao197 escribio':
> On Wed, 06 Jun 2007 14:11:18 +0400, Ary Manzana <ary at esperanto.org.ar>
> wrote:
>
>> Anyway, I'd like to see some real-world examples where const avoids
>> bugs. Because if those examples don't exist, then the keywords are
>> there just for compiler optimization.
>
> First example:
>
> class A
> {
> public :
> A() {}
> A( const A & o ) {}
> A & operator=( const A & o ) {}
>
> bool operator!() const { return false; }
> bool operator==( const A & o ) /*const*/ { return this == &o; }
> bool operator!=( const A & o ) /*const*/ { return !( *this = o ); }
> };
>
> Try find error there without const-modifiers and with them.
>
> Second example:
>
> #include <string>
>
> class OutgoingCall
> {
> public :
> const std::string &
> msisdn() const { return msisdn_; }
>
> void
> setMsisdn( const std::string & value ) { msisdn_ = value; }
>
> private :
> std::string msisdn_;
> };
>
> std::string
> makePlainNumber( std::string & msisdn )
> {
> if( '+' == msisdn[ 0 ] )
> msisdn.erase( 0, 1 );
> return msisdn;
> }
>
> void
> routeOutgoingCall( const OutgoingCall & call )
> {
> std::string plainNumber = makePlainNumber( call.msisdn() );
> }
>
> Because of const compiler doesn't allow me to call makePlainNumber from
> routeOutgoingCall. Without const this is allowed and makePlainNumber
> modifies routeOutgoingCall's argument 'call'.
>
> --Regards,
> Yauheni Akhotnikau
More information about the Digitalmars-d
mailing list