[C++-sig] export std::set

Andreas Beyer mail at a-beyer.de
Thu May 4 10:05:01 CEST 2006


François Duranleau wrote:

>
> If I may make a few suggestions:
>
>>      // element access
>>      bool contains(const KeyType key)
>>          { return count(key)>0; }
>>      // we must define add() for it gets explicit argument types
>>      void add(const KeyType key)
>>          { insert(key); }
>>      void remove(const KeyType key)
>>          // improve error handling here
>>          { if (!contains(key)) throw "element not in set"; 
>> erase(key);  }
>
>
> Why not put the key parameter as a const reference instead of copying?
>
Good point, no problem with contains() and remove(). Is there no risk 
with add()? What if the object that is passed to add() does not exist 
beyond its current scope? Like this:


void some_function(py_set<string>& a_set)
{
    string s = "hello world";
    a_set.add(s);
}
py_set<string> my_set;
some_function(my_set);
// Is it certain that 's' in 'my_set' still exists at this point?


> Also, for remove, it would probably be best to write it like this:
>
> void remove( const KeyType& key )
> {
>     typename source_type::iterator i = this->find( key ) ;
>     if ( i == this->end() )
>     {
>         throw "element not in set" ;
>     }
>     this->erase( i ) ;
> }
>
> This way you look up for the key only once, not twice.

Another good point.

>
> Also, everywhere in py_set<>, you need to either make all calls to 
> some base class's (with template arguments dependent on the current 
> class) method qualified (e.g. with this-> as above) or "import" them 
> with 'using' declarations, or else this code is not standard and won't 
> compile on some compilers (the one I use, g++-4.0, for instance).
>
Ups. I wasn't aware of that. Thanks for the warning!

Andreas




More information about the Cplusplus-sig mailing list