Transitive Const in OO programming
eao197
eao197 at intervale.ru
Wed Aug 8 05:18:49 PDT 2007
Hi!
I'm sorry, I haven't ability to follow D2.0 discussions last time, so may
be my question had been solved anywhere. But I wonder how to express in
D2.0 C++ classes like that:
// Collection of client's specific data.
class client_info_t
{
public :
client_info_t()
: m_socket( 0 )
, m_queue( 0 )
{}
//
// Getters/Setters.
//
ACE_SOCK_Stream *
socket() const { return m_socket; }
void
set_socket( ACE_SOCK_Stream * s ) { m_socket = s; }
ACE_Message_Queue *
queue() const { return m_queue; }
void
set_queue( ACE_Message_Queue * q ) { m_queue = q; }
private :
ACE_SOCK_Stream * m_socket;
ACE_Message_Queue * m_queue;
};
// Clients map.
class client_map_t
{
public :
...
// Puts new client info into map.
void
insert( const std::string & client_id, const client_info_t & info );
// Removes client info from map.
void
remove( const std::string & client_id );
// Fetches client info from map.
// Throws invalid_agrument if client_id is unknown.
const client_info_t &
fetch( const std::string & client_id ) const;
...
private :
std::map< std::string, client_info_t > m_map;
};
client_map_t::fetch is const method, so it doesn't allow anyone to change
map content. If someone wants to send some data to a client, it can use
const client_map_t::fetch() and retrive const client_info_t object. Then
he can use const client_info_t::socket() to send data via non-const
ACE_SOCK_Stream pointer. But he can't change content of client_info_t
because he has only const reference to client_info_t.
I could suggest that in D2.0 fetch() sould return object of different
type. For example:
class ConstrainedClientInfo
{
public :
this( SocketStream s, MessageQueue q ) { m_socket = s; m_queue = q; }
SocketStream socket() { return m_socket; }
MessageQueue queue() { return m_queue; }
private :
SocketStream m_socket;
MessageQueue m_queue;
}
and
class ClientMap
{
public :
...
ConstrainedClientInfo fetch( string client_id );
...
private :
ClientInfo[string] m_map;
};
But in such case ClientMap.fetch cannot be const (may be I'm wrong?)
because if ClientMap.fetch is const then m_map is also const and
ClientInfo reference from m_map is also const, and
SocketStream/MessageQueue references from ClientInfo from m_map is also
const.
--
Regards,
Yauheni Akhotnikau
More information about the Digitalmars-d
mailing list