避免临时的std ::字符串来调用的boost :: unordered_map ::找 [英] avoid temporary std::string to invoke boost::unordered_map::find
问题描述
我有以下类型:
boost::unordered_map< std::string , Domain::SomeObject > objectContainer;
这仅仅是一个映射到某个域对象,使用的std ::字符串
作为键。现在,的std ::字符串
可以构造和比为const char *
。 (不需要一个明确的的std ::字符串
暂时的,虽然也许是隐式转换是怎么回事?)
which is just a map to some domain object, using std::strings
as keys. Now, std::string
can be constructed and compared with const char*
. (no need for an explicit std::string
temporary, although maybe a implicit conversion is happening?)
问题发生时,我尝试做这样的事情。
The problem happens when I try to do something like
void findStuff(const char* key) {
auto it = objectContainer.find(key); //<---build error
}
我这里主要关注的是,它似乎有点有点矫枉过正建的std ::字符串
只是为了对一个inmutable比较 STD ::字符串
,因为的std ::字符串
临时会希望有自己的缓冲区,复制为const char *
在它的内容,然后用它来运行找到()
方法。
My main concern here is that it seems a little bit overkill to build a std::string
just to make a comparison against an inmutable std::string
, because the std::string
temporary will want to have its own buffer, copy the const char*
content in it, and then use that to run the find()
method.
有一个快捷方式,我可以使用,以避免在这里创建一个的std ::字符串
临时?
Is there a shortcut I can use to avoid the creation of a std::string
temporary in here?
推荐答案
当然。重新定义你的函数是这样的:
Of course. Redeclare your function like this:
void findStuff(std::string const & key);
现在使用的std ::字符串
从一开始就调用code正确。
Now use std::string
in the calling code right from the start.
这篇关于避免临时的std ::字符串来调用的boost :: unordered_map ::找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!