Re: using map, list etc. in const methods

From: Donovan Rebbechi (abuse_at_aol.com)
Date: 01/23/04


Date: Fri, 23 Jan 2004 20:15:08 +0000 (UTC)

In article <burtuq$hld$01$1@news.t-online.com>, Christof Krueger wrote:
> Donovan Rebbechi wrote:
 
>> It's not necessarily a bad thing. But you need to make sure that you understand
>> who "owns" a given pointer, and you need to make sure that the map doesn't hold
>> on to "dead pointers".
>>
>> Here's my question: how are your pointers allocated and deleted ? Who owns them ?
> In this case the board creates the nodes, stores them in the map and
> deletes them in it's destructor. I see that ownership is a question of
> design. Thanks!

I see.

But why not instead store the node in an automatic structure:

class Handle
{
    Node* impl;
  public:
    Handle(Node* x):impl(x) {}
    /*
      how you "handle" these is up to you ...
     Handle (const Handle& );
     Handle& operator= (const Handle&);
     */
    ~Handle() { delete impl; }
    Node& operator*() { return *impl; }
    const Node& operator*() const { return *impl; }
    Node* operator->(){ return impl; }
    const Node* operator->() const { return impl; }
};
 
> Another question:
> If I had a public method getNodeMap() that should return my nodes-map to
> the caller, is there a possibility to make this method const and to
> return a const version of the map,

You could make the function return a const reference to the map. But that's
a bad idea because it reveals implementation details.

A better approach would be to have begin() and end() methods that return
const_iterators and use a typedef to make it looks as though the map iterators
"belong" to the board class.

e.g.
class Board
{
  std::map<foo,bar> m;
public:
  typedef std::map< foo, bar>::const_iterator const_iterator;

  const_iterator begin() const { return m.begin(); }
  const_iterator end() const { return m.end(); }

Cheers,

-- 
Donovan Rebbechi
http://pegasus.rutgers.edu/~elflord/


Relevant Pages

  • Re: using map, list etc. in const methods
    ... >>Is there a proper way to leave the function const? ... return a const version of the map, so that the caller may not change the ... but failed because of a lot of compiler ...
    (comp.lang.cpp)
  • using map, list etc. in const methods
    ... through a "map" of CNode-pointers. ... CBoard::countPiecesconst ... At the moment I'm just using lists, ... maps in lack of a good book or online tutorial discussing the STL in detail. ...
    (comp.lang.cpp)
  • Re: Maps
    ... There are three const there. ... The first, just makes the map a constant, i.e. ... at least the SGI docs don't mention any restrictions like the ... You can only populate this via ...
    (microsoft.public.vc.stl)
  • Re: weird error
    ... You declared this member function "const". ... Indexing operator for 'map' template is a _non-const_ function. ...
    (comp.lang.cpp)