std ::用std :: string*作为键的映射

std::map with std::string* as key

本文关键字:std 映射 string      更新时间:2023-10-16

我正在使用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字段指向NULL0x2,但是当我插入地图时,键总是完好无损:

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