Stepping back and looking at constness from another angle.

eao197 eao197 at intervale.ru
Thu Jun 7 03:35:59 PDT 2007


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