【发布时间】:2014-03-09 00:41:43
【问题描述】:
我正在使用 std::map 和 const std::string 键,我认为避免将键推到堆栈周围会很好,所以我将键类型更改为指针:
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;
}
它工作了一段时间,然后我开始遇到字符串键失去胆量的段错误。 _M_p 字段指向 NULL 或 0x2,但当我插入地图时,键始终完好无损:
bars[new string(on_stack_string)] = bar;
在 gdb 中,new string(on_stack_string) 似乎将_M_p 字段指向正常的堆位置,而不是堆栈值。 std::string 有什么特别之处,它不能用在这样的数据结构中吗?也许我用钥匙做了一些其他愚蠢的事情,但我想不出它会是什么。
【问题讨论】:
-
std::string在内部使用堆分配的内存来存储字符数据。在 g++ 中,sizeof(std::string)是 24。因此,当您“认为避免将键推到堆栈周围会很好”时,您肯定在考虑其他事情。至于这个错误,可能和g++的copy on write有关。我敢打赌,非指针字符串会离开作用域并删除堆数据,因为指针字符串仅用作临时字符串且从未写入。 -
你是如何跟上字符串的?似乎您可能没有正确地重新计算字符串。也许使用 shared_ptr
-
不@KitsuneYMG,我没想到别的。我在这里问了这个问题,因为我不知道它是如何工作的。所以我需要有人向我解释,而不是因为我不知道我所问的问题而责备我。如果我知道它是如何工作的,我为什么要问它是如何工作的?
标签: c++ map segmentation-fault stdstring