Main problem is declare of your container.
boost::unordered_map< std::string , Domain::SomeObject > objectContainer;
If look to source we will see :
template<typename Key, typename Mapped, ...>
class unordered_map;
iterator find(const Key &);
So, you have strong restrictions by interface. Method find always use Key type as parameter and you can't change it without changing container key type.
If you sure that lose too many time on initialization of std::string you can use buffer (if no threads). For example :
class objectContainer : public boost::unordered_map<std::string, SomeObject>
{
std::string _buffer;
public:
typedef boost::unordered_map<std::string, SomeObject> inherited;
objectContainer() { _buffer.reserve(1024); }
typename inherited::iterator find(const char * key)
{
_buffer = key;
return inherited::find(_buffer);
}
};
Now, buffer allocates memory only once in constructor, not every time when call find.
Other way, use your own key type which can work std::string and const char *, but at this case you should to define implementation of Hash(boost::hash<Key>
), predicate ( std::equal_to<Key>
) with your Key type.
Something like this :
class Key
{
public:
virtual ~Key();
virtual const char * key() = 0; // for hash and predicate
};
// predicate
struct equal_to_Key : binary_function <Key,Key,bool> {
bool operator() (const Key & x, const Key & y) const
{
return false; // TODO : compare Key here
}
};
class CharKey : public Key
{
const char * _key;
public:
virtual const char * key() { return _key; }
};
class StringKey : public Key
{
std::string _key;
public:
virtual const char * key() { return _key.c_str(); }
};
Now, you have one way to get const char * and use it in hash and predicate. When you insert string you prefer to use StringKey. When find - CharKey.
boost::unordered_map< Key , Domain::SomeObject, KeyHashFunctor, equal_to_Key > objectContainer;
void findStuff(const char* key) {
auto it = objectContainer.find(CharKey(key));
}
But, at this case added virtual functions and creating Key objects might reduce perfomance and working with objectContainer became non-comfortable.