In my question insert or update in ptr_map I wanted to use the following code
typedef boost::ptr_map<const std::string, Entry> KeyEntryMap;
KeyEntryMap m;
void insertOrUpate(const char* key, Entry* entry) {
std::pair<KeyEntryMap::iterator, bool> re = m.insert(key, entry);
if (!re.second) {
m.replace(re.first, entry);
}
}
However, the following code from ptr_map insert releases (by auto_type) the entry object if an insert fails.
std::pair<iterator,bool> insert_impl( const key_type& key, mapped_type x ) // strong
{
this->enforce_null_policy( x, "Null pointer in ptr_map_adapter::insert()" );
auto_type ptr( x ); // nothrow
std::pair<BOOST_DEDUCED_TYPENAME base_type::ptr_iterator,bool>
res = this->base().insert( std::make_pair( key, x ) ); // strong, commit
if( res.second ) // nothrow
ptr.release(); // nothrow
return std::make_pair( iterator( res.first ), res.second ); // nothrow
}
I guess this is because ptr_map wants to ensure the ptr to insert is not leaked at the case. Does it mean we have to create a new entry object when calling replace? can we let ptr_map stop releasing it?
The alternative is using find first.
KeyEntryMap::iterator p = m.find(key);
if (p == m.end()) {
m.insert(key, entry);
return;
}
m.replace(p, entry);
Does this have more cost for insert case? It needs searching the map twice.