std ::用std :: string*作为键的映射
std::map with std::string* as key
我正在使用const std::string
键的std::map
,我认为避免在堆栈周围推动键,所以我将密钥类型更改为指针:
class less_on_star : less<const string*> {
public:
virtual bool operator() (const string* left, const string *right);
};
less_on_star::operator() (const string* left, const string *right) {
return *left < *right;
}
class Foo {
private:
map<const string*, Bar*, less_on_star> bars;
}
它工作了一段时间,然后我开始得到segfaults,其中字符串键失去了胆量。_M_p
字段指向NULL
或0x2
,但是当我插入地图时,键总是完好无损:
bars[new string(on_stack_string)] = bar;
在GDB中,new string(on_stack_string)
看来将_M_p
字段指向正常的堆位置,而不是堆栈值。std::string
是否有一些特殊的东西可以在这样的数据结构中使用?也许我用钥匙做了其他愚蠢的事情,但我想不到会是什么。
这需要轻量级,真的:
#include <boost/flyweight.hpp>
#include <map>
typedef boost::flyweight<std::string> string;
struct Bar
{
};
struct Foo {
std::map<string, Bar*> bars;
};
int main()
{
Foo foo;
foo.bars.insert(string("hello"), new Bar());
foo.bars.insert(string("world"), new Bar());
}
现在,为了对Bar*
元素有一些安全性,为什么不使用boost::ptr_map
?
相关文章:
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 将唯一指针插入std::映射
- 重载std::映射不同的密钥类型
- std::映射,只有move构造函数可用
- std::映射服装比较函数和函数/lambda错误
- std::映射导致插入时出现C2664错误
- 将从std::映射中获取的std::pair引用传递给接受std::对引用的函数
- std::映射键作为模板化结构与枚举成员
- std ::映射以构造为钥匙
- 在锁定下清除STD ::映射,而移动到临时对象
- 计算向量的std ::映射为键的值,并将双倍作为值
- 写入/读取 std::映射到二进制文件需要运算符
- 我如何正确地为std ::映射分配内存
- 如何打印包含整数和整数集的std::映射
- 在字符串的std::映射中找到编译错误,long
- 将std ::映射复制到std ::对向量
- 使用std ::映射的键的部分匹配
- 遍历std ::映射,效果少于迭代器之间的比较